在熊猫另一列上有条件的Groupby

我在执行以下操作时有一个数据框:

df1 = df.groupby('Date_1')['weight'].sum().reset_index(name='total_weight')

我正在尝试汇总特定日期的权重总和。

我想添加一个条件,使其仅在is_b为1时才求和。is_b是另一列,其中有2个值0和1。

任何人都可以建议如何在大熊猫中使用groupby条件。

谢谢

编辑

DF

Date_1    weight isBooked
01/09/2019  181  1
01/09/2019  189  1
01/09/2019  174  1
01/09/2019  267  1
01/09/2019  308  1
02/09/2019  79   0
02/09/2019  179  1
02/09/2019  435  1

请注意,数据框也有其他列,只需在此处发布相关字段即可。

wh1469 回答:在熊猫另一列上有条件的Groupby

您可以检查这是否是您要找的东西吗?

import pandas as pd
from io import StringIO
csv = StringIO('''Date_1    weight isBooked
        01/09/2019  181  1
        01/09/2019  189  1
        01/09/2019  174  1
        01/09/2019  267  1
        01/09/2019  308  1
        02/09/2019  79   0
        02/09/2019  179  1
        02/09/2019  435  1''')
df = pd.read_csv(csv,delim_whitespace=True)
df1 = df.loc[df.isBooked == 1 ].groupby('Date_1')['weight'].sum().reset_index(name='total_weight')
print(df1)

输出为

       Date_1  total_weight
0  01/09/2019          1119
1  02/09/2019           614
,

您可以groupby进行乘法运算的结果:

(df['weight'] * df['isBooked']).groupby(df['Date_1']).sum()

输出:

Date_1
01/09/2019    1119
02/09/2019     614
dtype: int64
本文链接:https://www.f2er.com/3147304.html

大家都在问