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
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.