[英]Python- I want to move second row's column to first row column using pandas
I have csv data like this 我有像这样的csv数据
column1 column2
A 12
A 13
B 15
B 16
C 12
C 14
I want to merge rows with same value in column 1 by creating another column3 or say transpose like this 我想通过创建另一个column3来合并第1列中具有相同值的行,或者像这样说transpose
column1 column2 column3
A 12 13
B 15 16
C 12 14
I'm using pandas and want to run some loop for this, probably. 我正在使用熊猫,并希望为此运行一些循环。
use groupby
with cumcount
to set an index then unstack
使用groupby
与cumcount
设置一个索引然后unstack
c = 'column1'
s = df.set_index([c, df.groupby(c).cumcount() + 2]).column2
s.unstack().add_prefix('column').reset_index()
column1 column2 column3
0 A 12 13
1 B 15 16
2 C 12 14
This will handle if there are uneven numbers of groups as well. 如果组的数量不均匀,这将处理。
Consider the df
考虑一下df
column1 column2
A 12
A 13
B 15
B 16
B 16
C 12
C 14
C 14
C 14
Then 然后
c = 'column1'
s = df.set_index([c, df.groupby(c).cumcount() + 2]).column2
s.unstack().add_prefix('column').reset_index()
column1 column2 column3 column4 column5
0 A 12.0 13.0 NaN NaN
1 B 15.0 16.0 16.0 NaN
2 C 12.0 14.0 14.0 14.0
If you wanted to fill those NaN
ahead of time, use the fill_value
parameter in unstack
如果你想填补这些NaN
时间提前,使用fill_value
参数unstack
c = 'column1'
s = df.set_index([c, df.groupby(c).cumcount() + 2]).column2
s.unstack(fill_value=0).add_prefix('column').reset_index()
column1 column2 column3 column4 column5
0 A 12 13 0 0
1 B 15 16 16 0
2 C 12 14 14 14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.