[英]Map index of one dataframe to column of another dataframe
I know there are questions similar to this but they do not answer my question, so kindly bear with me.我知道有类似的问题,但他们没有回答我的问题,所以请多多包涵。
I have 2 data frames df1 and df2.我有 2 个数据框 df1 和 df2。
In df1, the Order ID1 is the index and the Payment column is empty.在 df1 中,Order ID1 是索引,Payment 列是空的。
print(df1)
Order ID1 Sale Price Payment
OD1 45
OD2 55
OD3 56
In df2, the Order ID2 is the index.在 df2 中,Order ID2 是索引。
print(df2)
Order ID2 paid value
OD1 44
OD3 41
OD2 33
I am trying to map the index of df1 (Order ID1) to the index of df2 (Order ID2) and return the corresponding paid value
in the empty payment
column.我正在尝试将 df1(订单 ID1)的索引 map 转换为 df2(订单 ID2)的索引,并在空
payment
列中返回相应的paid value
。 Basically I am performing a look up procedure.基本上我正在执行查找过程。
I tried using the map function as follows:-我尝试使用 map function 如下: -
df2['Payment'] = df2.index.map(df1.index)
but I am getting the following error:但我收到以下错误:
TypeError: 'Index' object is not callable
Update : if Order IDX
is already the index of your 2 dataframes, use simply assignment:更新:如果
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
Old answer旧答案
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
That's because you are trying to map the index.那是因为您正在尝试 map 索引。 You first need to create a dictionary with keys being the index of df2 and values being the paid value using
dict(zip())
.您首先需要创建一个字典,其中键是 df2 的索引,值是使用
dict(zip())
的付费值。 Then you can map that on df1.index
and return it into your Payment column:然后您可以在 df1.index 上的
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.