【问题标题】:Transform pandas dataframe as per the image below根据下图转换熊猫数据框
【发布时间】:2022-01-23 13:40:25
【问题描述】:

请帮助我了解在下图中对 pandas DataFrame 进行转换的最佳方法是什么。

dct = {'section': {0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3},
 'friendly': {0: 5, 1: 5, 2: 5, 3: 4, 4: 3, 5: 1, 6: 2, 7: 5, 8: 5}}
df = pd.DataFrame(dct)

5 : 优秀 4:非常好 3:好 2:还好 1:差

输入:

输出:

【问题讨论】:

    标签: python pandas stack pivot unpivot


    【解决方案1】:

    使用crosstab 进行计数,然后通过除以sum 得到df2 的百分比,将concatkeys 连接为MultiIndex,对其进行排序并在map 中展平:

    d = {5 : 'Excellent', 4 : 'Very Good', 3 : 'Good', 2 : 'Just Okay', 1 : 'Poor'}
    
    df1 = pd.crosstab(df['section'], df['friendly'])
    df2 = df1.div(df1.sum(axis=1), axis=0).mul(100).round().astype(int)
    
    df = (pd.concat([df1, df2], keys=('Count','Per'), axis=1)
            .sort_index(axis=1, ascending=[False, True], level=[1,0])
            .rename(columns=d))
    
    df.columns = df.columns.map(lambda x: f'{x[1]}_{x[0]}')
    df = df.reset_index()
    print (df)
       section  Excellent_Count  Excellent_Per  Very Good_Count  Very Good_Per  \
    0        1                3             75                1             25   
    1        2                0              0                0              0   
    2        3                2             67                0              0   
    
       Good_Count  Good_Per  Just Okay_Count  Just Okay_Per  Poor_Count  Poor_Per  
    0           0         0                0              0           0         0  
    1           1        50                0              0           1        50  
    2           0         0                1             33           0         0  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2021-04-03
      • 2018-07-12
      • 2021-05-27
      相关资源
      最近更新 更多