鉴于此数据框:
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
)
我想将数据框转换为:
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
...
...
答案 0 :(得分:6)
您可以使用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
中的新内容):
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