python - 将数据帧的行与同一组合并并将值分配给新列

标签 python python-3.x pandas pandas-groupby

我想将数据帧的行与同一组合并并将值分配给新列

之前

     x          y         group
0   0.333333    1.000000    0
1   0.750000    0.137931    0
2   1.000000    0.270115    0
3   0.272727    1.000000    1
4   0.727273    0.124294    1
5   1.000000    0.355932    1
6   0.272727    1.000000    2
7   0.727273    0.096591    2
8   1.000000    0.363636    2
9   0.272727    1.000000    3
10  0.727273    0.105556    3
11  1.000000    0.416667    3
12  0.272727    1.000000    4
13  0.727273    0.181818    4
14  1.000000    0.443182    4

之后

     x1          y1         x2          y2              x3          y3
    0.333333    1.000000    0.750000    0.137931    1.000000    0.270115    
    0.272727    1.000000    0.727273    0.124294    1.000000    0.355932    
    0.272727    1.000000    0.727273    0.096591    1.000000    0.363636    
    0.272727    1.000000    0.727273    0.105556    1.000000    0.416667    
    0.272727    1.000000    0.727273    0.181818    1.000000    0.443182    

最佳答案

这是使用pivot_table的一种方法:

# rank of the row within each group
cats = df.groupby('group').group.rank('first').astype(int)

# use pivot_table to transform data
new_df = pd.pivot_table(df, index='group', columns=cats)

# rename to get desired columns
new_df.columns = [f'{x}{y}' for x,y in new_df.columns]

输出:

             x1        x2   x3   y1        y2        y3
group                                                  
0      0.333333  0.750000  1.0  1.0  0.137931  0.270115
1      0.272727  0.727273  1.0  1.0  0.124294  0.355932
2      0.272727  0.727273  1.0  1.0  0.096591  0.363636
3      0.272727  0.727273  1.0  1.0  0.105556  0.416667
4      0.272727  0.727273  1.0  1.0  0.181818  0.443182

关于python - 将数据帧的行与同一组合并并将值分配给新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58171778/

相关文章:

python - Gdal 在多次安装后不会导入 (Mac OSX)

python - 存储函数时如何传递预定义参数

python - 一行与多行的 boolean 比较

python-3.x - 由于 PortAudio 库问题 (OSError),Windows 上的 PyInstaller 可执行文件无法运行

Python Pandas : get average number of decimal

Python3 ftplib 无法获取更大的二进制文件

python - 为什么 dict.get(key) 而不是 dict[key]?

python - imshow 彩色图像,错误显示为蓝色

python - 在大文件上使用 Pandas 数据透视表的最有效方法

python - 组合 Pandas DataFrame 中的数字列值以获取重复行而不组合字符串