pandas df 转换:比 df.unstack().unstack() 更好的方法
pandas df transformation: a better way than df.unstack().unstack()
正在尝试将 pandas 数据帧从宽格式转换为长格式。
我已经尝试 melt()
, use wide_to_long()
(简单的 melt()
),但一直对我收到的语法和输出感到困惑。
我还通读了 SO 和网络上有关此主题的许多帖子,并尝试了 proposed 方法,但结果从来都不是我想要的。
帮助我发现了 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("Whosebug"), 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 ?
但这确实很笨重,必须有更好的方法!
谢谢,祝你有美好的一天:)
使用T
wide_df.T
Out[1108]:
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 ?
正在尝试将 pandas 数据帧从宽格式转换为长格式。
我已经尝试 melt()
, use wide_to_long()
(简单的 melt()
),但一直对我收到的语法和输出感到困惑。
我还通读了 SO 和网络上有关此主题的许多帖子,并尝试了
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("Whosebug"), 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 ?
但这确实很笨重,必须有更好的方法!
谢谢,祝你有美好的一天:)
使用T
wide_df.T
Out[1108]:
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 ?