Skip to main content
 首页 » 编程设计

python之根据 python pandas 中的标志拆分列值

2024年10月24日12pander-it

我有一个表格如下:

Sex weight hight 
M    34      5'6" 
F    29      5'1" 
M    29      4'5" 
F    26      5'2" 

我想通过 python pandas 显示如下表

M                 F 
Height Weight    Height Weight 
5'6"   34        5'1"     29 
4'5"   29        5'2"     26 

平行比较男性和女性的 Ht 和 wt 数据。

请您参考如下方法:

丑陋但有效。这个想法是将原始的 DataFrame 按性别分成两部分,然后将它们与分层列索引重新组合。

# Test data 
df =pd.DataFrame({'Sex': ['M','F','M','F'], 'Weight': [34,29,29,26], 'Height': [5.6,5.1,4.5,5.2]}) 
 
def reshape(grouped, group): 
    df = grouped.get_group(group).loc[:,['Height','Weight']] 
    df.columns = [[group, group],df.columns] 
    return df.reset_index(drop=True) 
 
grouped = df.groupby('Sex') 
pd.concat([reshape(grouped,'M'), reshape(grouped,'F')], axis=1) 
 
       M             F        
  Height Weight Height Weight 
0    5.6     34    5.1     29 
1    4.5     29    5.2     26