我正在尝试以有效的方式计算可能具有不匹配数据的两组之间的差异。
以下数据框,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']
上使用列表理解。分成两个数据帧,但随后我在减去不匹配的情况下仍然遇到类似的问题。
最佳答案
对代码进行分组,然后用 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
关于python - 减去数据框中各组之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641623/