pandas 数据框如何合并列 [英] Pandas Data Frame how to merge columns
问题描述
我在图片中有一个熊猫数据框.我如何将其变成下表所示的表格. (演示是在excel中进行的,但我只想向您说明表的外观-这个问题与从excel导入和导出数据框无关)
I have a pandas dataframe like in the picture. How can I turn it into the table like below. (the demonstration is in excel but I just want to illustrate to you how the table look like- this question does not related to importing and exporting dataframe from/to excel)
谢谢您
推荐答案
这是不可能的.
pandas.DataFrame
的基础对象是numpy
数组,它们不会按照您建议的方式对数据进行分组.因此,不能将任意列显示为分组数据.
Underlying pandas.DataFrame
objects are numpy
arrays, which do not group data in the way you suggest. Therefore, an arbitrary column cannot be displayed as grouped data.
选项1
可以通过使用MultiIndex来部分复制所需的输出:
It is possible to partially replicate your desired output by using MultiIndex:
import pandas as pd
df = pd.DataFrame([['AAA', 8, 2, 'BBB'],
['AAA', 9, 5, 'BBB'],
['AAA', 10, 6, 'BBB']],
columns=['Name', 'Score1', 'Score2', 'PM'])
res = df.set_index(['Name', 'PM'])
结果:
Score1 Score2
Name PM
AAA BBB 8 2
BBB 9 5
BBB 10 6
选项2
或者您可以在3列上添加一个虚拟列和set_index
:
Or you can add a dummy column and set_index
on 3 columns:
df['dummy'] = 0
res = df.set_index(['Name', 'PM', 'dummy'])
结果:
Score1 Score2
Name PM dummy
AAA BBB 0 8 2
0 9 5
0 10 6
这篇关于 pandas 数据框如何合并列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!