首页 > 解决方案 > 计算两个 Pandas DataFrame 中列之间的分数差异

问题描述

我正在尝试为不同列中具有相同值的行计算两个 DataFrame 中 >20 列之间的分数差异。

例如给定两个数据框:

df1 = index, A, B, C, D, ID
        0,   2, 1, 5, 4, -2
        1,   1, 2, 2, 4, -1
        2,   2, 4, 8, 8,  0 
        3,   1, 4, 6, 5,  1

df2 = index, A, B, C, D, ID
        0,   2, 1, 2, 2, -3
        1,   4, 3, 3, 2, -2
        2,   6, 2, 4, 6,  -1 
        3,   1, 4, 2, 4,  0

df3['A'] = (df1['A']-df2['A'])/df1['A']对于每一列(AD),如果行具有相同的 ID 值,我想获得分数差异(即)。任一数据帧中可能有没有通用 ID 的行,这些行不应包含在 df3.xml 中。

期望的输出:

df3 = index,  A,  B,   C,   D,  ID
        0,   -1,  -2, 0.4, 0.5, -2 
        1,   -5,  0,  -1,  -0.5, -1
        2,   0.5, 0, 0.75, 0.5,  0

最终,我还想获得 df3 中 AD 列每一行的这些分数差异的平方和(即所示示例的 32.72)

标签: pythonpandasdataframe

解决方案


您将希望ID在两个数据帧上都设置为索引,然后您可以直接获取数据帧的差异。下面的代码将完成您正在寻找的内容:

样本数据

df1 = pd.DataFrame(
        [[0,   2, 1, 5, 4, -2],
        [1,   1, 2, 2, 4, -1],
        [2,   2, 4, 8, 8,  0 ],
        [3,   1, 4, 6, 5,  1]], columns = ['index', 'A', 'B', 'C', 'D', 'ID'])

df2 = pd.DataFrame(
        [[0,   2, 1, 2, 2, -3],
        [1,   4, 3, 3, 2, -2],
        [2,   6, 2, 4, 6,  -1 ],
        [3,   1, 4, 2, 4,  0]], columns = ['index', 'A', 'B', 'C', 'D', 'ID'])

分数差分

df1 = df1.set_index('ID') # set index for fractional differencing
df2 = df2.set_index('ID') # set index for fractional differencing
target_cols = ['A', 'B', 'C', 'D'] # define columns to use in differencing
df3 = (df1[target_cols] - df2[target_cols]) / df1[target_cols] # get fractional difference
df3 = df3.dropna().reset_index() # remove row observations without intersecting IDs in df1 and df2

输出

print(df3.to_string())
   ID     A     B     C     D
0  -2 -1.00 -2.00  0.40  0.50
1  -1 -5.00  0.00 -1.00 -0.50
2   0  0.50  0.00  0.75  0.50

推荐阅读