首页 > 解决方案 > 在数据框中的组之间减去值

问题描述

我正在尝试以有效的方式计算可能具有不匹配数据的两组之间的差异。

以下数据框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']来拆分为两个数据帧,但随后我仍然遇到关于减去不匹配案例的类似问题。

标签: pythonpandas

解决方案


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

推荐阅读