Pandas用旧的列名生成一个新的数据帧

2024-06-28 19:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来组织数据。所以我有以下数据帧(称为df): the original dataframe

我想根据Mean-CArea,Mean-chpressure和Mean-u-Force对数据帧进行分组。但是,我得到了以下结果:

wrongresult

如您所见,列名是0,1,2,不是原生的,解剖的,非解剖的。有没有办法从原始数据帧中获取正确的列名?在

以下是我目前为止的代码:

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

先谢谢你!在


Tags: 数据nameindffor原始数据meanhead
2条回答

您想使用xs

df.xs('Mean_CArea', axis=1, level=1)

以及

^{pr2}$

以及

df.xs('Mean_Force', axis=1, level=1)

IIUC您可以按列(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

相关问题 更多 >