在两个Pandas DataFrame中计算列之间的分数差异

3

我将尝试计算两个数据框中具有相同值的不同列之间的分数差异。

例如,给定两个数据框:

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

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

期望输出:

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 中 A-D 列的每行的这些分数差的平方和(例如,对于所示示例为 32.72)。
1个回答

3
你可以在两个DataFrame上都将ID设置为索引,然后直接对这两个DataFrame进行差分。下面的代码将实现你所需的功能:

示例数据

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

1
好答案,也许把你的最后一行改成 df3.dropna().reset_index() 可以得到期望的输出。除此之外,+1。 - Erfan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接