【问题标题】:Clean the data based on condition pandas根据条件 pandas 清理数据
【发布时间】:2020-02-12 17:32:02
【问题描述】:

我有一个如下图所示的数据框

ID      Unit_ID      Price    Duration
1       A            200      2
2       B            1000     3
2       C            1000     3
2       D            1000     3
2       F            1000     3
2       G            200      1
3       A            500      2
3       B            200      2

从上述数据框中,如果 ID、Price 和 Duration 相同,则用平均替换价格(价格除以此类组合的计数)。

例如从上面的数据帧中第 2 行到第 5 行的 ID、Price 和 Duration 相同,这意味着它的计数是 4,所以新的 Price = 1000/4 = 250。

预期输出:

ID      Unit_ID      Price    Duration
1       A            200      2
2       B            250      3
2       C            250      3
2       D            250      3
2       F            250      3
2       G            200      1
3       A            500      2
3       B            200      2

【问题讨论】:

    标签: pandas pandas-groupby


    【解决方案1】:

    GroupBy.transformGroupBy.size 一起使用,Series 的大小与原来的大小相同,由计数填充,因此可能除以Series.div

    df['Price'] = df['Price'].div(df.groupby(['ID','Price','Duration'])['Price'].transform('size'))
    print (df)
       ID Unit_ID  Price  Duration
    0   1       A  200.0         2
    1   2       B  250.0         3
    2   2       C  250.0         3
    3   2       D  250.0         3
    4   2       F  250.0         3
    5   2       G  200.0         1
    6   3       A  500.0         2
    7   3       B  200.0         2
    

    详情

    print (df.groupby(['ID','Price','Duration'])['Price'].transform('size'))
    0    1
    1    4
    2    4
    3    4
    4    4
    5    1
    6    1
    7    1
    Name: Price, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2021-06-04
      • 2020-07-16
      • 2021-06-23
      相关资源
      最近更新 更多