[英]Python pandas how to transpose df : value of columns to value of rows?
Original df:原始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让我们尝试使用附加键分配
cumcount
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)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.