pandas - Pandas Vlookup 2 DF 列不同长度并执行计算
问题描述
考虑到具有相同列名的两个 df 的 diff 长度,我需要执行类似 vlookup 的计算。假设我有一个名为 df1 的 df,例如:
Y M P D
2020 11 Red 10
2020 11 Blue 9
2020 11 Green 12
2020 11 Tan 7
2020 11 White 5
2020 11 Cyan 17
和第二个 df 称为 df2 例如:
Y M P D
2020 11 Blue 4
2020 11 Red 12
2020 11 White 6
2020 11 Tan 7
2020 11 Green 20
2020 11 Violet 10
2020 11 Black 7
2020 11 BlackII 3
2020 11 Cyan 14
2020 11 Copper 6
我需要一个新的 df df3['Res','P']
,比如 2 列显示从 df2 中减去 df1 的结果,例如:
Res P
Red -2
Blue 5
Green -8
Tan 0
White -1
Cyan 3
我无法通过查找然后在网上计算找到任何东西。我尝试将 df1 和 df2 合并为一个 df,但是当“P”列中的值匹配时,我看不到如何执行计算。我认为 df1 和 df2 的合并可能是第一步吗?
解决方案
- 基于示例,列
'Y'
和'M'
合并无关紧要。如果这些列是相关的,则使用带有on
参数的列表(例如on=['Y', 'M', 'P']
)。- 目前,仅
[['P', 'D']]
使用df1
和中的列df2
。
- 目前,仅
- 下面的代码产生了示例的期望输出,但很难说更大的数据帧会发生什么以及
'P'
.
import pandas as pd
# setup the dataframes
df1 = pd.DataFrame({'Y': [2020, 2020, 2020, 2020, 2020, 2020], 'M': [11, 11, 11, 11, 11, 11], 'P': ['Red', 'Blue', 'Green', 'Tan', 'White', 'Cyan'], 'D': [10, 9, 12, 7, 5, 17]})
df2 = pd.DataFrame({'Y': [2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020], 'M': [11, 11, 11, 11, 11, 11, 11, 11, 11, 11], 'P': ['Blue', 'Red', 'White', 'Tan', 'Green', 'Violet', 'Black', 'BlackII', 'Cyan', 'Copper'], 'D': [4, 12, 6, 7, 20, 10, 7, 3, 14, 6]})
# merge the dataframes
df = pd.merge(df1[['P', 'D']], df2[['P', 'D']], on='P', suffixes=('_1', '_2')).rename(columns={'P': 'Res'})
# subtract the values
df['P'] = (df.D_1 - df.D_2)
# drop the unneeded columns
df = df.drop(columns=['D_1', 'D_2'])
# display(df)
Res P
0 Red -2
1 Blue 5
2 Green -8
3 Tan 0
4 White -1
5 Cyan 3
推荐阅读
- python - 在python中的类中定义字典
- excel - 从文件夹中导入第一张纸,除了一个命名文件导入第二张纸
- c# - 如何在 Connect App for Business Central 中以编程方式使用 Azure Active Directory 进行身份验证?
- wordpress - 当他们访问结帐页面时,Easy Digital Downloads 被重定向到特定页面是空的
- python - 通过索引读取 csv 文件中的列
- oracle - 如何使用 case 语句创建行值
- javascript - javascript中调用的这种形式或语法是什么?
- npm - IBM Blockchain Platform 扩展 npm 错误
- python - 在类上调用方法并手动传递实例是否总是等同于在实例上调用方法?
- machine-learning - 如何使用 xml 文件中的对象训练对象检测模型?