Pandas:如何将行中的一列旋转为列
问题描述
鉴于此数据框:
feature score searchTerm
0 a 0.534509 pizza
1 b 0.586020 pizza
2 c 0.588972 pizza
3 a 0.566261 chinese
4 b 0.572405 chinese
5 c 0.489369 chinese
6 a 0.499068 thai
7 b 0.431068 thai
8 c 0.441617 thai
功能仅限于 (a
,b
,c
)
我想把数据框转成这个:
I want to pivot the dataframe into this:
a b c searchTerm
0.534509 0.586020 0.588972 pizza
0.566261 0.572405 0.489369 chinese
0.499068 0.431068 0.441617 thai
...
...
解决方案
你可以使用pivot
:
df1 = df.pivot(index='searchTerm', columns='feature', values='score').reset_index()
print (df1)
feature searchTerm a b c
0 chinese 0.566261 0.572405 0.489369
1 pizza 0.534509 0.586020 0.588972
2 thai 0.499068 0.431068 0.441617
最后你可以通过 删除列名rename_axis
(pandas
0.18.0
中的新功能):
Last you can remove columns name by rename_axis
(new in pandas
0.18.0
):
df1 = df1.rename_axis(None, axis=1)
#pandas bellow 0.18.0
#df.columns.name = None
print (df1)
searchTerm a b c
0 chinese 0.566261 0.572405 0.489369
1 pizza 0.534509 0.586020 0.588972
2 thai 0.499068 0.431068 0.441617
相关文章