【问题标题】:Map index of one dataframe to column of another dataframe将一个数据帧的索引映射到另一个数据帧的列
【发布时间】:2022-01-24 07:47:39
【问题描述】:

我知道有 questions 与此类似,但他们没有回答我的问题,所以请多多包涵。

我有 2 个数据框 df1 和 df2。

在df1中,Order ID1为索引,Payment列为空。

print(df1)

Order ID1    Sale Price     Payment
OD1             45            
OD2             55
OD3             56

在df2中,Order ID2是索引。

print(df2)

Order ID2     paid value
OD1             44
OD3             41
OD2             33

我正在尝试将 df1(订单 ID1)的索引映射到 df2(订单 ID2)的索引,并在空的 payment 列中返回相应的 paid value。基本上我正在执行查找过程。

我尝试使用地图功能如下:-

df2['Payment'] = df2.index.map(df1.index)

但我收到以下错误:

TypeError: 'Index' object is not callable

【问题讨论】:

  • 我建议使用pandas.merge 在 ID 列上加入两个 DataFrame。这将为您提供一个包含所有三列的新 DataFrame。
  • 使用merge代替map函数有什么特别的好处吗?

标签: python pandas dataframe vlookup


【解决方案1】:

更新:如果 Order IDX 已经是您的 2 个数据帧的索引,请使用简单的赋值:

df1['Payment'] = df2['paid value']
print(df1)

# Output:
           Sale Price  Payment
Order ID1                     
OD1                45       44
OD2                55       33
OD3                56       41

旧答案

df1['Payment'] = df1['Order ID1'].map(df2.set_index('Order ID2').squeeze())
print(df1)

# Output:
  Order ID1  Sale Price  Payment
0       OD1          45       44
1       OD2          55       33
2       OD3          56       41

【讨论】:

    【解决方案2】:

    那是因为您正在尝试映射索引。您首先需要创建一个字典,其中键是 df2 的索引,值是使用 dict(zip()) 的付费值。然后您可以将其映射到 df1.index 并将其返回到您的付款列:

    df1['payment'] = df1.index.map(dict(zip(df2.index,df2['paid value'])))
    
               Sale Price  payment
    Order ID1                     
    OD1                45       44
    OD2                55       33
    OD3                56       41
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 1970-01-01
      • 2019-10-17
      • 2023-03-15
      • 1970-01-01
      • 2023-03-21
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多