Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在dataframe中组合多行并创建新列_Python_Pandas_Dataframe - Fatal编程技术网

Python 在dataframe中组合多行并创建新列

Python 在dataframe中组合多行并创建新列,python,pandas,dataframe,Python,Pandas,Dataframe,在我的数据框中,每行有动态的列数,一条记录可以包含超过一行。前两列是关键列。如果键列匹配,我必须将每行数据追加到一行中,并创建追加所需的列 输入位于列c2中的(数据帧)c1下方的列等中 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 我尝试使用df.groupby(\uuuuuuuuuuuuuuuuuuuuuu

在我的数据框中,每行有动态的列数,一条记录可以包含超过一行。前两列是关键列。如果键列匹配,我必须将每行数据追加到一行中,并创建追加所需的列

输入位于列c2中的(数据帧)c1下方的列等中

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
我尝试使用df.groupby(\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。在python中有任何函数可以实现这一点吗

所需输出:(数据帧)

用于列表理解中的一系列计数器,然后和最后一个展平
多索引

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
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