python - 在数据框中的组之间减去值
问题描述
我正在尝试以有效的方式计算可能具有不匹配数据的两组之间的差异。
以下数据框df
,
df = pd.DataFrame({'type': ['A', 'A', 'A', 'W', 'W', 'W'],
'code': ['1', '2', '3', '1', '2', '4'],
'values': [50, 25, 25, 50, 10, 40]})
有两种“代码”不匹配的类型——特别是“W”类型不存在代码 3,“A”类型不存在代码 4。我将代码包装为字符串,因为在我的特定情况下它们有时是字符串。
我想减去两种类型之间匹配代码的值,以便我们获得,
result = pd.DataFrame({'code': ['1', '2', '3', '4'],
'diff': [0, 15, 25, -40]})
标志将指示哪种类型具有更大的价值。
我在这里花了一些时间检查 groupby diff 方法的变化,但没有看到任何处理两个可能不匹配的列之间减法的特定问题。相反,大多数问题似乎都适合 diff() 方法的预期用途。
我最近尝试的路线是在 上使用列表理解df.groupby['type']
来拆分为两个数据帧,但随后我仍然遇到关于减去不匹配案例的类似问题。
解决方案
Groupby 在代码上,然后用 0 替换缺失值
df = pd.DataFrame({'type': ['A', 'A', 'A', 'W', 'W', 'W'],
'code': ['1', '2', '3', '1', '2', '4'],
'values': [50, 25, 25, 50, 10, 40]})
def my_func(x):
# What if there are more than 1 value for a type/code combo?
a_value = x[x.type == 'A']['values'].max()
w_value = x[x.type == 'W']['values'].max()
a_value = 0 if np.isnan(a_value) else a_value
w_value = 0 if np.isnan(w_value) else w_value
return a_value - w_value
df_new = df.groupby('code').apply(my_func)
df_new = df_new.reset_index()
df_new = df_new.rename(columns={0:'diff'})
print(df_new)
code diff
0 1 0
1 2 15
2 3 25
3 4 -40
推荐阅读
- django - 获取一公里距离的所有经纬度
- c++ - 编译应该将任意大数字表示为字符串的 C++ 程序时出现逻辑错误
- docker - 有没有办法通过终端在 Docker for Mac 上启用 Kubernetes?
- spring - 春季自动配置
- python - 矩阵的整数数组索引后的维度不一致
- angular - 以角度动态加载嵌套组件?
- django - sorl.thumbnail 没有在我的视图中创建缩略图
- node.js - Node JS 插件 - NAN 与 N-API?
- sass - 您可以从外部托管 (cdn) sass 文件中导入 sass 变量并在您的项目中使用它吗?
- python - 从 Flask 中的 HTTP POST 请求中读取图像文件并将其转换为 PIL 图像