首页 > 解决方案 > 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 的合并可能是第一步吗?

标签: pandasdataframevlookupcalculation

解决方案


  • 基于示例,列'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

推荐阅读