【发布时间】:2017-09-25 20:11:56
【问题描述】:
尝试将 pandas DataFrames 从宽格式转换为长格式。
我试过melt(),使用wide_to_long()(简单的melt()),但一直对我收到的语法和输出感到困惑。
我还阅读了 SO 和网络上有关此主题的许多帖子,并尝试了 quite some proposed 方法,但结果从来不是我想要的。
This post 帮助我发现了unstack() - 我终于设法得到了我想要的结果连续使用两次:df.unstack().unstack()。
我确信这不是最好的方法,我希望得到提示!这是我的例子:
import pandas as pd
# an example df (the real data makes more sense):
series_list = [
pd.Series(list("hello! hello!"), name='greeting'),
pd.Series(list("stackoverflow"), name='name'),
pd.Series(list("howsit going?"), name='question')
]
wide_df = pd.DataFrame(series_list)
创建这样的 df 总是会给我一个 wide 格式的文件:
0 1 2 3 4 5 6 7 8 9 10 11 12
greeting h e l l o ! h e l l o !
name s t a c k o v e r f l o w
question h o w s i t g o i n g ?
但是,我希望 pd.Series()s name= 属性成为列名。
对我有用的是上面提到的df.unstack().unstack():
greeting name question
0 h s h
1 e t o
2 l a w
3 l c s
4 o k i
5 ! o t
6 v
7 h e g
8 e r o
9 l f i
10 l l n
11 o o g
12 ! w ?
但这肯定很笨拙,必须有更好的方法!
谢谢,祝你有美好的一天:)
【问题讨论】:
-
你只需要转置wide_df.T
标签: python pandas dataframe transformation