dpwqb 2020-01-27 13:58 采纳率: 33.3%
浏览 3519
已结题

pandas:pivot_table计算占比

例子:

>>>df=pd.DataFrame({
                 "A": ["foo", "foo", "foo", "foo", "foo",
                        "bar", "bar", "bar", "bar"],
                 "B": ["one", "one", "one", "two", "two",
                          "one", "one", "two", "two"],
                 "C": ["small", "large", "large", "small",
                       "small", "large", "small", "small",
                       "large"],
                 "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                 "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>>df
     A    B      C  D  E
0  foo  one  small  1  2
1  foo  one  large  2  4
2  foo  one  large  2  5
3  foo  two  small  3  5
4  foo  two  small  3  6
5  bar  one  large  4  6
6  bar  one  small  5  8
7  bar  two  small  6  9
8  bar  two  large  7  9

>>>table=pd.pivot_table(df, values='D', index=['A', 'B'], 
                        aggfunc=len)

>>>table
         D
A   B     
bar one  2
    two  2
foo one  3
    two  2

请问如何计算每个不同A值和B值下D所占的比例?能提供pivot_table实现最好,groupby也行。

  • 写回答

1条回答

  • HMMHMH 2020-01-27 15:39
    关注
    import pandas as pd
    
    df = pd.DataFrame({
        "A": ["foo", "foo", "foo", "foo", "foo",
              "bar", "bar", "bar", "bar"],
        "B": ["one", "one", "one", "two", "two",
              "one", "one", "two", "two"],
        "C": ["small", "large", "large", "small",
              "small", "large", "small", "small",
              "large"],
        "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
        "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
    count = df.shape[0]
    pivot_table = df.pivot_table(index='A', columns='B', values='D', aggfunc='count')
    pivot_table = pivot_table.apply(lambda x: x / count)
    print(pivot_table)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64