[英]merge row with next row in dataframe pandas
I have a dataframe in pandas which contains multiple columns. 我在pandas中有一个数据框,其中包含多个列。 I want to merge every row with the next row. 我想将每一行与下一行合并。 Example: 例:
input dataframe: 输入数据框:
A B C
a1 a2 a3
b1 b2 b3
c1 c1 c3
d1 d2 d3
output dataframe: 输出数据帧:
A1 B1 C1 A2 B2 C2
a1 a2 a3 b1 b2 b3
b1 b2 b3 c1 c2 c3
c1 c2 c3 d1 d2 d3
d1 d2 d3 NaN NaN NaN
The solusion I came up with was copying the original dataframe, changing the index to be index - 1, and then merging the two data frames by index. 我想到的解决方案是复制原始数据帧,将索引更改为index-1,然后按索引合并两个数据帧。 Is there any other solution? 还有其他解决方案吗?
Use shift
with join
, concat
or assign
, for new columns names add_suffix
is useful: 使用shift
与join
, concat
或assign
,对新列的名称add_suffix
是有用的:
df1 = df.add_suffix('1').join(df.shift(-1).add_suffix('2'))
df1 = pd.concat([df.add_suffix('1'), df.shift(-1).add_suffix('2')], axis=1)
df1 = df.add_suffix('1').assign(**df.shift(-1).add_suffix('2'))
print (df1)
A1 B1 C1 A2 B2 C2
0 a1 a2 a3 b1 b2 b3
1 b1 b2 b3 c1 c1 c3
2 c1 c1 c3 d1 d2 d3
3 d1 d2 d3 NaN NaN NaN
You could use 你可以用
In [204]: pd.concat([df.add_suffix(1), df[1:].reset_index(drop=True).add_suffix(2)],
axis=1)
Out[204]:
A1 B1 C1 A2 B2 C2
0 a1 a2 a3 b1 b2 b3
1 b1 b2 b3 c1 c1 c3
2 c1 c1 c3 d1 d2 d3
3 d1 d2 d3 NaN NaN NaN
And, extend it to generic use 并且,将其扩展为通用
In [206]: N = 3 # Say 3 more times
In [207]: pd.concat([df.add_suffix(1)] +
[df[x+1:].reset_index(drop=True).add_suffix(x+2)
for x in range(N)], axis=1)
Out[207]:
A1 B1 C1 A2 B2 C2 A3 B3 C3 A4 B4 C4
0 a1 a2 a3 b1 b2 b3 c1 c1 c3 d1 d2 d3
1 b1 b2 b3 c1 c1 c3 d1 d2 d3 NaN NaN NaN
2 c1 c1 c3 d1 d2 d3 NaN NaN NaN NaN NaN NaN
3 d1 d2 d3 NaN NaN NaN NaN NaN NaN NaN NaN NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.