簡體   English   中英

計算兩個 Pandas DataFrame 中列之間的分數差異

[英]Calculate fractional difference between columns in two 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

並且對於每一列(AD),我想獲得的分數差(即df3['A'] = (df1['A']-df2['A'])/df1['A']如果行具有相同的 ID 值。 任一數據框中可能都有沒有通用 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 中 AD 列每一行的這些小數差的平方和(即所示示例為 32.72)

您需要將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM