合并pandas dataframe中的多行并创建新列

2024-09-29 01:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据帧中每行的列数是动态的,单个记录可以超过1行。前2列是键列。如果键列匹配,我必须将每一行数据追加到一行中,并根据追加所需创建尽可能多的列。在

输入在(数据帧)c1以下的列c2中的列等。。。在

row 1: A 1 c1 c2 c3.. c20
row 2: A 1 c21....c25
row 3. A 1 c26.... c35
row 4: A 2 d1 d2... d21
row 5: A 2 d22....d27

我试着用分组数据框(\uuUu first 2列名)。first().reset\u index(),它只返回第一行,因为我们使用的是first()。在python中有什么函数可以做到这一点吗

需要输出:(数据帧)

^{pr2}$

Tags: 数据记录动态rowfirstd1c2c1
1条回答
网友
1楼 · 发布于 2024-09-29 01:31:38

使用^{}表示一系列计数器,然后在列表理解中使用^{}^{}和最后一个展平MultiIndex

print (df)
       a  b    c    d    e    f
row1:  A  1   c1   c2   c3  c20
row2:  A  1  c21  c22  c23  c24
row3.  A  1  c26  c27  c28  c29
row4:  A  2   d1   d2  d21  d22
row5:  A  2  d22  d27  d28  d29

s = df.groupby(['a','b']).cumcount()

df1 = df.set_index(['a', 'b', s]).unstack().sort_index(level=1, axis=1)
df1.columns = [f'{x}{y}' for x, y in df1.columns]
df1 = df1.reset_index()
print (df1)
   a  b  c0  d0   e0   f0   c1   d1   e1   f1   c2   d2   e2   f2
0  A  1  c1  c2   c3  c20  c21  c22  c23  c24  c26  c27  c28  c29
1  A  2  d1  d2  d21  d22  d22  d27  d28  d29  NaN  NaN  NaN  NaN

相关问题 更多 >