merge row with next row in dataframe pandas

笑着哭i 提交于 2020-01-01 17:37:48

问题


I have a dataframe in pandas which contains multiple columns. 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. Is there any other solution?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/47450259/merge-row-with-next-row-in-dataframe-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!