python - 在 Pandas 中使用 SUMIF 创建新行

标签 python pandas

如何使用 pandas 根据条件创建一个包含总和的新行?

初始表 -

Product   Date  CAT    Value
Product A Apr   F31    100
Product A Apr   F32    200
Product A Apr   F45    300
Product A Apr   F46    400
Product A May   F31    200
Product A May   F32    300
Product A May   F45    400
Product A May   F46    500
Product B Apr   F31    200
Product B Apr   F32    300
Product B Apr   F45    400
Product B Apr   F46    500
Product B May   F31    600
Product B May   F32    700
Product B May   F45    800
Product B May   F46    900

我想通过将 F31 和 F32 组合成 F3 来创建这个,它应该给我值的总和。

Product   Date  CAT    Value
Product A Apr   F3     300
Product A Apr   F45    300
Product A Apr   F46    400
Product A May   F3     500
Product A May   F45    400
Product A May   F46    500
Product B Apr   F3     500
Product B Apr   F45    400
Product B Apr   F46    500
Product B May   F3    1300
Product B May   F45    800
Product B May   F46    900

你能帮我吗?

最佳答案

为了创建上面提到的 DataFrame,我们需要应用两个操作。

  1. 字符串.replace

  2. .groupby 与聚合,即 .sum().reset_index()

  3. 字符串替换方法用于替换字符串中的字符,通过该方法我们可以将字符串F31、F32转换为F3。

    .replace('F31','F3')

    .replace('F32','F3')

  4. .groupby 方法用于根据给定的约束来分离数据。此方法将数据分成可以执行操作的 block 。在这里,我们需要根据多个列对数据进行分组。

然后,我们需要根据'CAT'列聚合值(value)列的总和,即首先按“产品”分组,然后按“日期”分组,最后按“CAT”分组。因此,为此我们使用 .sum()

之后的结果将是一个分组对象,但是为了将其转换为DataFrame,我们需要使用.reset_index(),该方法允许填充基于输入条件列具有相应值的列。

Data.groupby(['Product','Date','CAT'])['Value'].sum().reset_index(name='Value')

代码片段如下所示:

Product = ['Product A','Product A','Product A','Product A','Product A','Product A','Product A','Product A','Product B','Product B','Product B','Product B','Product B','Product B','Product B','Product B']

Date = ['Apr','Apr','Apr','Apr','May','May','May','May','Apr','Apr','Apr','Apr','May','May','May','May']

CAT = ['F31','F32','F45','F46','F31','F32','F45','F46','F31','F32','F45','F46','F31','F32','F45','F46']

Value = [100, 200,300,400,200,300,400,500,200,300,400,500,600,700,800,900]

# Creating Data Frame

Data = pd.DataFrame({'Product':Product,'Date':Date,'CAT':CAT,'Value':Value})

# String Replace

Data['CAT'] = Data['CAT'].replace('F31','F3')

Data['CAT'] = Data['CAT'].replace('F32','F3')

# Group By Operation

DataG = pd.DataFrame(Data.groupby(['Product','Date','CAT'])['Value'].sum().reset_index(name='Value'))

应用上述操作之前的数据。

Data Before applying above operations

应用上述操作后的数据。

Data After applying above operations

关于python - 在 Pandas 中使用 SUMIF 创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64105001/

相关文章:

python - 用于附加带有新结果的文件的脚本 - 序列预期错误

python - 将列表中的值附加到列表

python - Python 中的 Raspberry PI 服务器/客户端套接字

Python:是否有更好的方法从 pandas 的 DataFrame 中删除数据范围?

python - 在 Python 中将具有多个特征的分类数据转换为数字的最快方法是什么?

python - 使用 .loc 访问器的 pandas 日期时间索引的 bool 掩码

python - 创建非冗余相关矩阵Python最有效的方法?

python - 创建一个描述其他列中缺失值的列

python - 有没有办法在 Python 中对函数的每一行进行修饰/执行操作?

python - Pandas 中的自定义时间序列重采样