[英]Copy value from one dataframe to another based on multiple column index
I have 2 dataframes:我有 2 个数据框:
df1 =
item shop revenue
0 1 0 0.0
1 2 1 0.0
2 3 2 0.0
df2 =
item shop revenue
0 1 0 33
1 2 1 244
2 3 2 124
3 4 3 26
I want to map the value of revenue from df2
based on the item and shop equality.我想 map 基于商品和商店相等的来自df2
的收入值。 I do this in a painful way first by combining two columns and using them as index.我首先通过组合两列并将它们用作索引以一种痛苦的方式做到这一点。 Then I map the value and finally I drop the extra columns.然后我 map 的值,最后我删除了额外的列。
df1['new_id']=df1["shop"].astype(str) +"_"+ df1["item"].astype(str)
df2['new_id']=df2["shop"].astype(str) +"_"+ df2["item"].astype(str)
df1 = df1.set_index("new_id")
df1.update(df2.set_index("new_id"))
df1 = df1.reset_index()
df1 = df1.drop(['new_id'],axis=1)
df2 = df2.drop(['new_id'],axis=1)
df1 =
item shop revenue
0 1 0 33.0
1 2 1 244.0
2 3 2 124.0
There must a better and more concise way of doing this with a simpler code.必须有一种更好、更简洁的方法来使用更简单的代码来做到这一点。 Could you please advise me on a better approach?你能告诉我更好的方法吗?
You can use DataFrame.merge
by select 2 columns in df1
and no on
parameter for merge by intersection of columns:您可以使用DataFrame.merge
by select df1
中的 2 列,并且没有on
参数用于通过列的交集进行合并:
df = df1[['item','shop']].merge(df2)
So it working same like:所以它的工作方式相同:
df = df1[['item','shop']].merge(df2, on=['item','shop'])
Your solution should be changed with DataFrame.set_index
by 2 columns for MultiIndex
:您的解决方案应使用MultiIndex
更改为DataFrame.set_index
2 列:
df11 = df1.set_index(['item','shop'])
df11.update(df2.set_index(['item','shop']))
df = df11.reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.