python - Pandas 使用旧的列名创建一个新的数据框

标签 python pandas dataframe multiple-columns

我需要一些帮助构建数据。所以我有以下 DataFrame(称为 df): the original dataframe

我想根据 Mean_CArea、Mean_CPressure 和 Mean_Force 对数据帧进行分组。但是,我得到了以下结果:

wrongresult

正如您所看到的,列名称是 0,1,2,而不是 NATIVE_RH、ANATOMICAL_RH 和 NON_ANATOMICAL_RH。有没有办法从原始数据框中获取正确的列名称?

这是迄今为止我的代码:

def function(self, df):
    d = dict()
    for head in df.columns.tolist():
        RH, j_mechanics = head
        if j_mechanics not in d:
            d[j_mechanics] = df[head]
        else:
            d[j_mechanics] = pd.concat([d[j_mechanics],df[head]], axis=1, ignore_index=True)
    for df_name, df in sorted(d.items()):
        print(df_name)
        print(df.head())

提前非常感谢!

最佳答案

IIUC您可以使用swaplevelgroupby按列 (axis=1) 和按第一级 (level=0):

df = pd.DataFrame({('B', 'a'): {0: 4, 1: 10}, ('B', 'b'): {0: 5, 1: 11}, ('B', 'c'): {0: 6, 1: 12}, ('A', 'a'): {0: 1, 1: 7}, ('A', 'c'): {0: 3, 1: 9}, ('A', 'b'): {0: 2, 1: 8}})

print (df)
   A         B        
   a  b  c   a   b   c
0  1  2  3   4   5   6
1  7  8  9  10  11  12
df.columns = df.columns.swaplevel(0,1)

for i, g in df.groupby(level=0, axis=1):
    print (g)
   a    
   A   B
0  1   4
1  7  10
   b    
   A   B
0  2   5
1  8  11
   c    
   A   B
0  3   6
1  9  12

关于python - Pandas 使用旧的列名创建一个新的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343419/

相关文章:

python - 在 bash 中使用 NULL 字节(缓冲区溢出)

python - 如何用 Pandas 创建高低开收盘图表

python - 如何根据匹配日期连接两个数据框?

Python内部排序方法

python - 一对多关系-google datastore-python

python - 使用 mod_wsgi 在 Apache2 上部署 Python Falcon

python - Pandas dataframe - 将某些行或单元格格式化为 2 d.p

python - 删除空行和数据行在 DataFrame pandas 中不匹配

scala - Spark、Scala 中的数组操作

python - 如果满足条件,重命名 pandas 数据框中的列