【问题标题】:Mean grouped by two columns with window by 3 months and NaN for less than 3 months由两列分组的平均值,窗口为 3 个月,NaN 少于 3 个月
【发布时间】:2020-05-24 00:28:32
【问题描述】:

我必须按客户、帐户在此数据集中应用平均值计算,但此平均值需要每 3 个月应用到这些组中。对于没有3个月的客户A1200,结果需要NaN

customer    account    month        invoice
C1000       A1100      2019-10-01   34000
                       2019-11-01   55000
                       2019-12-01   80000
            A1200      2019-10-01   90000
                       2019-11-01   55000
            A1300      2019-10-01   10000
                       2019-11-01   10000
                       2019-12-01   20000
C2000       A2100      2019-10-01   78000
                       2019-11-01   55000
                       2019-12-01   80000

我尝试使用此命令,但平均值看起来不正确。

df_3m.groupby(['customer','account']).mean()

pandaspyspark 中是否有一些想法?

【问题讨论】:

  • 只是为了确认分组没有满三个月,那么不要对相应的金额做任何事情。只需将金额替换为nan?如果有 4 个月,计算前 3 个月的平均值并将第 4 个月的金额替换为 nan,会发生什么情况?

标签: python python-3.x pandas pyspark pandas-groupby


【解决方案1】:

数据

+----------+---------+----------+----------+
| customer | account |  month   |  invoice |
+----------+---------+----------+----------+
| C1000    | A1100   | 01-10-19 |    34000 |
| C1000    | A1100   | 01-11-19 |    55000 |
| C1000    | A1100   | 01-12-19 |    80000 |
| C1000    | A1200   | 01-10-19 |    90000 |
| C1000    | A1200   | 01-11-19 |    55000 |
| C1000    | A1300   | 01-10-19 |    10000 |
| C1000    | A1300   | 01-11-19 |    10000 |
| C1000    | A1300   | 01-12-19 |    20000 |
| C2000    | A2100   | 01-10-19 |    78000 |
| C2000    | A2100   | 01-11-19 |    55000 |
| C2000    | A2100   | 01-12-19 |    80000 |
+----------+---------+----------+----------+

您的查询

res = df_3m.groupby(['customer','account']).mean()

查询以过滤具有less than 3 months 的帐户

lt_3 = df.groupby(['account']).count() >2

最终结果

res[lt_3]

输出

+----------+---------+--------------+
| customer | account |   invoice    |
+----------+---------+--------------+
| C1000    | A1100   | 56333.333333 |
|          | A1200   | NaN          |
|          | A1300   | 13333.333333 |
| C2000    | A2100   | 71000.000000 |
+----------+---------+--------------+

【讨论】:

    【解决方案2】:

    你可以试试这个:

    df['month'] = pd.to_datetime(df['month'])
    df = df.groupby(by=['customer', 'account']).mean()[df.groupby(by=['customer', 'account']).count() > 2].reset_index()
    print(df)
    

    输出:

      customer account       invoice
    0    C1000   A1100  56333.333333
    1    C1000   A1200           NaN
    2    C1000   A1300  13333.333333
    3    C2000   A2100  71000.000000
    

    【讨论】:

    • 嘿,太好了!它完美地工作!我不知道这个技巧[df_3m.groupby(by=['customer', 'account']).count() > 2],这是什么?以及它如何与另一部分代码结合?
    • 条件就是这样,如下所示:df[df['number'] < 100],您只选择df 中列number 的值小于100 的行
    猜你喜欢
    • 2019-12-16
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多