python - 应用条件分组

标签 python pandas

我有一个数据框,其中包含两个月值列,分别为“month1”和“month2”。如果“month1”列中的值不是“NA”,则根据“month1”列对相应的“amount”值求和。如果“month1”列中的值为“NA”,则将“month2”列中相应的“amount”值相加。

import pandas as pd
df = pd.DataFrame({'month1': [1,2,'NA', 1, 4, 'NA', 'NA'],
          'month2': ['NA',5,1, 2, 'NA', 1, 3],
          'amount': [10,20,40, 50, 60, 70, 100]})

输入输出数据框如下:

输入数据框

   month1  month2  amount
0     1.0     NaN      10
1     2.0     5.0      20
2     NaN     1.0      40
3     1.0     2.0      50
4     4.0     NaN      60
5     NaN     1.0      70
6     NaN     3.0     100

输出数据框

最佳答案

因为您的 NA 值是字符串,您可以简单地对两列进行 groupby:

# ignore month2 if month1 is NA
df.loc[df.month1.ne('NA'), 'month2'] = 'NA'

# groupby and sum
df.groupby(['month1','month2']).amount.transform('sum')

如果你不想改变你的数据,你可以这样做

s = np.where(df.month1.ne('NA'), 'NA', df['month2'])

df.groupby(['month1', s]).amount.transform('sum')

输出:

0     60
1     20
2    110
3     60
4     60
5    110
6    100
Name: amount, dtype: int64

关于python - 应用条件分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57513978/

相关文章:

java - 在Java程序中运行Python文件

python - 基于两列值相等的 Pandas 将列中的字段设置为 0

python - 使用 Shell Executor 在 GitLab Config yml 文件中为 CI-CD 激活 Conda 环境

python - 字符串的子集

python - 并行处理大量数据

python - 尝试在 python 中进行无缓冲读取时出现奇怪的换行符

python - 将带有百分比字符串的列更改为 float pandas 数据框

python - 如何在 Pandas 中的 groupby 中进行滚动窗口聚合?

python - 不同数据框的模糊匹配列

python - 按 pandas 中的操作分组