Pandas:如何将行中的一列旋转为列 [英] Pandas: How to pivot one column in rows into columns

查看:27
本文介绍了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

这篇关于Pandas:如何将行中的一列旋转为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆