【问题标题】:Sum all values in dataframe column grouped by one column and depending on other column value对按一列分组并取决于其他列值的数据框列中的所有值求和
【发布时间】:2019-11-04 08:25:55
【问题描述】:

我在特定月份为每个人都有一个数字,用整数表示。我需要为每个人添加这些数字,直到每行的指定日期。我想在 python DataFrame 上使用 apply 函数来使其具有可扩展性。

例如:

df = pd.DataFrame(
{'number': [10, 20 , 30, 40, 50], 'individual': ["John", "John" , "Eleonor", "Eleonor", "Eleonor"], 'date': [1, 2, 3, 4, 5]})

df=

   number individual  date
0      10       John     1
1      20       John     2
2      30    Eleonor     3
3      40    Eleonor     4
4      50    Eleonor     5

当日期严格低于行中的数字时,我想对数字求和,如果没有日期符合条件的行,则输入 NA。 这里的结果是:

   number individual  date
0      NA       John     1
1      10       John     2
2      NA    Eleonor     3
3      30    Eleonor     4
4      70    Eleonor     5

【问题讨论】:

  • “当日期严格低于行中的日期时”我不确定你的意思
  • 对于每一行,只有当日期的整数小于当前行的整数时,才需要将值相加

标签: python pandas dataframe conditional-statements apply


【解决方案1】:

我根据要求找到了使用 apply 方法的解决方案,它允许与 dask 一起使用:

df['number'] = df.groupby("individual")['number'].apply(lambda x: x.expanding().sum().shift())

产生

   number individual  date
0     NaN       John     1
1    10.0       John     2
2     NaN    Eleonor     3
3    30.0    Eleonor     4
4    70.0    Eleonor     5

【讨论】:

    【解决方案2】:
    df = pd.DataFrame({'num': [10, 20 , 30, 40, 50], 
                       'ind': ["John", "John" , "Eleonor", "Eleonor", "Eleonor"], 
                       'date': [1, 2, 3, 4, 5]})
    
    df['x'] = df.groupby('ind')['num'].shift()
    df['y'] = df.groupby('ind')['x'].cumsum()
    print(df)
    

    产量

       num      ind  date     x     y
    0   10     John     1   NaN   NaN
    1   20     John     2  10.0  10.0
    2   30  Eleonor     3   NaN   NaN
    3   40  Eleonor     4  30.0  30.0
    4   50  Eleonor     5  40.0  70.0
    

    【讨论】:

    • 谢谢,没想到这么简单。当我在我的数据框上执行此操作时,我得到 AttributeError: 'SeriesGroupBy' object has no attribute 'shift'。你知道为什么吗?
    • 我找到了原因,因为我使用的是不支持 shift() 的 dask。谢谢你的回答!
    猜你喜欢
    • 2018-02-15
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多