python - 计算两个 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)
解决方案
您将希望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
推荐阅读
- python - 将列表转换为数组的 Numpy 问题
- swift - 放弃对 iOS 12 的支持时仍会收到 INStartAudioCallIntent (INStartCallIntent)
- java - 如果自动增量字段不是第一个,jOOQ 可以支持复合主键吗
- python - 从字典中删除对象
- ruby - 是否可以“重新推送”在 rubygems.org 上以相同版本发布的 yanked 版本 gem?
- php - 使用 str_replace 在韩语字符中显示菱形问号字符
- vue.js - 通过分页在 b-table 上显示剩余的 API 数据
- python - 当列表的元素值为列表时如何在Python中摆脱列表
- arrays - Powershell:单击 GUI 上的按钮移动到数组中的下一个项目
- amp-html - 如何在使用 CKEDITOR 动态创建的正文部分中显示来自非 AMP 标记的 AMP 标记