在数据框 pandas 中将行与下一行合并 [英] merge row with next row in dataframe pandas

查看:85
本文介绍了在数据框 pandas 中将行与下一行合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在pandas中有一个数据框,其中包含多个列.我想将每一行与下一行合并. 示例:

I have a dataframe in pandas which contains multiple columns. I want to merge every row with the next row. Example:

输入数据框:

A   B   C
a1  a2  a3
b1  b2  b3
c1  c1  c3
d1  d2  d3

输出数据框:

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

我想到的解决方案是复制原始数据帧,将索引更改为index-1,然后按索引合并两个数据帧. 还有其他解决方案吗?

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. Is there any other solution?

推荐答案

使用 shift concat assign ,对于新列名称, add_suffix 是有用:

Use shift with join, concat or assign, for new columns names add_suffix is useful:

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

这篇关于在数据框 pandas 中将行与下一行合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆