简体   繁体   中英

Python pandas how to transpose df : value of columns to value of rows?

Original df:

df=pd.DataFrame({'name':['id1','id1','id2','id2','id2'],
             'attr1':['a','b','c','d','e']})
    Out[45]: 
  name attr1
0  id1     a
1  id1     b
2  id2     c
3  id2     d
4  id2     e

What I want is:

在此处输入图片说明

The system requires more details but I have nothing to say so please do not view these words here, which will waste your time.

Let us try assign cumcount with additional key

s = df.assign(key=df.groupby('name').cumcount()+1).pivot('name','key','attr1')

s
Out[125]: 
key   1  2    3
name           
id1   a  b  NaN
id2   c  d    e

Just do

  1. groupby column
  2. add lambda agg func
  3. split to columns.

df.groupby('name') .agg(lambda x: '|'.join(x)) .attr1.str.split('|',expand=True)

combine above three

>> df.groupby('name').agg(lambda x: '|'.join(x)).attr1.str.split('|',expand=True)

      0  1     2
name            
id1   a  b  None
id2   c  d     e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM