Python:将列值的行收集到一行

标签 python pandas

我的原始数据框如下:

A B C D
2 10 39 109
1 8 40 111
3 9 38 108
2 11 41 107
3 13 40 112
2 12 39 113

我想要的输出是(根据 A 列值合并行):

A B C D A1 B1 C1 D1 A2 B2 C2 D2
2 10 39 109 11 41 107 12 39 113
1 8 40 111 NA NA NA NA NA NA
3 9 38 108 13 40 112 NA NA NA

最佳答案

使用GroupBy.cumcountDataFrame.unstack reshape :

g = df.groupby('A').cumcount()
df1 = df.set_index(['A',g]).unstack().sort_index(level=1, axis=1)
df1.columns = [f'{a}{b}' if b != 0 else a for a, b in df1.columns]
df1 = df1.reset_index()
print (df1)
   A     B     C      D    B1    C1     D1    B2    C2     D2
0  1   8.0  40.0  111.0   NaN   NaN    NaN   NaN   NaN    NaN
1  2  10.0  39.0  109.0  11.0  41.0  107.0  12.0  39.0  113.0
2  3   9.0  38.0  108.0  13.0  40.0  112.0   NaN   NaN    NaN

df = df.apply(pd.Categorical)
g = df.groupby('A').cumcount()
df1 = df.set_index(['A',g]).unstack().sort_index(level=1, axis=1)

df1 = df1.apply(lambda x: x.cat.add_categories([0])).fillna(0)
df1.columns = [f'{a}{b}' if b != 0 else a for a, b in df1.columns]
df1 = df1.reset_index()
print (df1)

   A   B   C    D  B1  C1   D1  B2  C2   D2
0  1   8  40  111   0   0    0   0   0    0
1  2  10  39  109  11  41  107  12  39  113
2  3   9  38  108  13  40  112   0   0    0

关于Python:将列值的行收集到一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67964868/

相关文章:

python - 附加继承对执行速度的影响

python - 使用抽象模型定义字段关系

python pandas - 如何将 1 个数据帧中的值映射到另一个数据帧中的索引而不循环?

python - 使用正则表达式从电子邮件 header 中查找 IP 地址

python - 将数据框从长格式转换为宽格式并动态命名列

python - Cherrypy + Autobahn websocket 在同一端口上

pandas - 根据条件每行使用不同的子字符串

Python:如何读取具有不同分隔符的csv文件?

python - 根据 lengt 函数从 df 内的数组中检索值

python - Matplotlib:双 y 轴图未对齐