python - 选择性分组依据,np.where Pandas/Python 查询

标签 python pandas numpy

df_有

A  B C
1  1  10
1  1  10
1  2  5
1  3  6
1  4  7

df_想要

A  B C    D
1  1  10  20
1  1  10  20
1  2  5   5
1  3  6   6
1  4  7   7

仅当 B 列为 1 或 2 时,才尝试按 A 列和 B 列分组。如果 B 为 1 或 2,则将 D 列输出为 C 列的 SUM。否则保持设置列 D = 列 C。

示例代码报错:

df_want['D']=np.where((df_want['B'].isin([1,2]), 
             df_want['A','B'].map(df_want.groupby(['A','B'])['C'].sum()), 
             df_want['C'])

问题出现在这里:df_want['A','B'].map.. 如果我只放 df_want.A.map 那么代码运行但输出错误。如果 col B 是 1 或 2,我只需要它来映射总和

最佳答案

sum 更改为 transform('sum')

np.where(df_want['B'].isin([1,2]), 
             df_want.groupby(['A','B'])['C'].transform('sum'), df_want['C'])

关于python - 选择性分组依据,np.where Pandas/Python 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633962/

相关文章:

python - 将排名有序的列添加到 Pandas Dataframe

python - 在 Python 中计算两个图像之间的绝对差之和的最快方法是什么?

python - 获取索引范围内行的最大值

python-3.x - 寻找一种有效的迭代方式

linux - 导入错误 : No module named ce_libs. 实用程序.Logger

python - 如何读取 pandas dataframe 中的 json 并将一列值更改为大写并保存 json 文件

Python xml解析etree按位置查找元素X

python - 在两个列表中查找匹配的子串

python - 如何在python中按条件排序

python - CherryPy:创建在 apache2 后面运行的 Web 服务 (mod_wsgi)