Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - Pandas: How to pivot one column in rows into columns

Given this dataframe:

   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

Feature is limited to (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
   ...
   ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use 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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...