[英]How to combine multiple rows into single row by adding columns with pandas?
I need to combine multiple rows into a single row with pandas, depending on the column 'hash' 我需要将多行与大熊猫合并为一行,具体取决于“哈希”列
View of my dataframe: 我的数据框视图:
hash a b
0 1 1 6
1 1 2 7
2 1 3 8
3 2 4 9
4 2 5 10
I want the dataframe to be converted like this: 我希望数据帧像这样转换:
hash a a1 a3 b b1 b2
0 1 1 2 3 6 7 8
1 2 4 5 nan 9 10 nan
I have tried to use some code related to groupby or transpose the whole dataframe but cant figure out how to do it. 我试图使用一些与groupby相关的代码或转置整个数据帧,但无法弄清楚该怎么做。 Anyone could help me out? 有人可以帮我吗?
Create MultiIndex
by set_index
with counter column by cumcount
, reshape by unstack
and flatten Multiindex
by map
with join
: 建立MultiIndex
由set_index
与计数器列cumcount
,通过重塑unstack
和扁平Multiindex
通过map
与join
:
df1 = df.set_index(['hash', df.groupby('hash').cumcount().add(1).astype(str)]).unstack()
df1.columns = df1.columns.map(''.join)
df1 = df1.reset_index()
print (df1)
hash a1 a2 a3 b1 b2 b3
0 1 1.0 2.0 3.0 6.0 7.0 8.0
1 2 4.0 5.0 NaN 9.0 10.0 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.