【问题标题】:How to find the variance between two groups in python pandas? [closed]如何在 python pandas 中找到两组之间的差异? [关闭]
【发布时间】:2020-02-15 16:48:59
【问题描述】:

我有一个这样的数据框,

ID   total_sec   is_weekday
1      300           1
1      200           0
2      280           1
2      260           0
3      190           1
4      290           0
5      500           1
5      520           0

我想找到工作日和周末之间差异最大的 ID。如果我们错过了工作日或周末的记录,我们将方差计算为 0。 我的预期输出是,

ID   variance
1       100
2       20
3       0
4       0
5       20

【问题讨论】:

  • 所以你想要最大的差异?总是只有两个吗?那么工作日和周末呢?你想要工作日和周末的区别吗?
  • ID 总是有 2 行吗?如果不能,你能发布一个更好的例子吗:)谢谢
  • @LeoE 有些ID只有一个。所以我想将差异计算为0
  • 嗨@anky_91 不,有些 ID 只有其中一个。所以我在 ID ='3' 和 ID='4' 中提到了 0 的区别。
  • 我认为下面带有.abs() 的答案应该可以回答您的问题

标签: python pandas numpy dataframe


【解决方案1】:

你可以这样做:

df.pivot(index="ID", columns="is_weekday", values="total_sec").diff(axis=1)[1].fillna(0)

输出:

ID
1    100.0
2     20.0
3      0.0
4      0.0
5    -20.0
Name: 1, dtype: float64

【讨论】:

    【解决方案2】:

    只要您可以保证每个 ID 有 1-2 行,并且每行都有不同的 'is_weekday' 值,那么您真的只需要“峰到峰” (ptp) 值。如果没有,请弄清楚如何解决 ['ID', 'is_weekday'] 上的重复问题,然后使用 ptp

    import numpy as np
    
    df.groupby('ID').total_sec.agg(np.ptp)
    

    ID
    1    100
    2     20
    3      0
    4      0
    5     20
    Name: total_sec, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多