python - 如果某些列的单元格值符合特定条件,如何分组并求和

标签 python pandas dataframe group-by pandas-groupby

我觉得我正在尝试做的事情非常基础,但我似乎无法在这里找到类似的帖子。如果我的帖子确实重复,请告诉我。

我拥有的数据是关于交通事故的。前两列显示了事件的确切死伤人数,但第 3 和第 4 列(酒精和手机相关)仅显示二进制值:0(表示不相关)和 1(表示相关)。

示例数据如下:

(抱歉,数据与列标题没有完全对齐,我从来不知道如何正确格式化它。如果有人能分享任何提示,我将不胜感激。)

    NAME FATAL# INJURY# ALCOHOL CELL
0   City A  5   1   0   0
1   City B  5   1   0   1
2   City A  3   1   1   0
3   City B  3   1   1   0
4   City A  3   0   1   0
5   City B  2   2   0   0

我想要的是对前两列进行分组求和,然后在 ALCOHOLCELLPHONE 时计算每个城市的 FATAL 总和 列单元格值为 1。

所以基本上我想要的输出是:

   NAME FATAL# INJURY # ALCOHOL FATALCELL FATAL
0   City A  11  2   6   0
1   City B  10  4   3   5

抱歉格式错误,上述数据框的图片如果有助于理解:

我有什么

Have

我想要什么

Want

我知道对于前两列,我将执行 df.groupby(['NAME']).['FATAL', 'INJURIES'].sum()。至于第二部分,我可以做 df1.groupby(['NAME','ALCOHOL_RELATED'])['FATAL_COUNT', 'INJURY_COUNT'].sum() 但是我会失去总计数列。

我该如何完成?

谢谢。

最佳答案

有时将附加系列加入数据框是最清楚的,然后 groupby:

df = pd.DataFrame({'NAME': ['CityA', 'CityB', 'CityA', 'CityB', 'CityA', 'CityB'],
                   'FATAL#': [5, 5, 3, 3, 3, 2],
                   'INJURY#': [1, 1, 1, 1, 0, 2],
                   'ALCOHOL': [0, 0, 1, 1, 1, 0],
                   'CELL': [0, 1, 0, 0, 0, 0]})

# construct fatals dataframe and join
fatals = df.iloc[:, -2:].mul(df['FATAL#'], axis=0).add_prefix('FATAL_')
df = df.join(fatals)

# define columns to sum and groupby
sum_cols = ['FATAL#', 'INJURY#'] + df.columns[-2:].tolist()
res = df.groupby('NAME')[sum_cols].sum().reset_index()

print(res)

    NAME  FATAL#  INJURY#  FATAL_ALCOHOL  FATAL_CELL
0  CityA      11        2              6           0
1  CityB      10        4              3           5

关于python - 如果某些列的单元格值符合特定条件,如何分组并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769351/

相关文章:

python - 如何使Python中的多个if语句运行得更快

python - 从段落中挑选最相关的词

python - Selenium Python 3.4.3 登录 Gmail : Password section

python - 子类化日期时间 : Is there a better way to maintain resulting object type after arithmetic operations?

pandas - Pandas 箱线图中的 mustache 究竟说明了什么?

python - Pandas 从对象到 bool 值的转换总是使用 astype 返回 True

python - Pandas:保存某一类别特有的行

python - pickle 序列化: module '__main__' has no attribute 'tokenize'

python - 从 Pandas Dataframe 中提取 Frozenset 项目

python - Pandas concat 具有不同的索引