Pandas:如何将行中的一个列透视为列

15

给定这个数据框:

   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
   ...
   ...
1个回答

17
你可以使用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接