简体   繁体   中英

To fill a dataframe column by values in another dataframe column values

I have 2 dataframes:

df1 = 
  item  sale
0   7   10.0
1   4   10.0
2   6   10.0
3   5   10.0
4   5   10.0
5   6   10.0
6   4   10.0

df2 =
   item sale
0   1   7
1   2   6
2   3   5
3   4   4
4   5   3

I want to change the values of df1 sales column, taking the values from df2 sales column.

I use the code:

df1.loc[df1.item.isin(df2.item), ['sale']] = df2[['sale']]

And I get

df1 =
item    sale
0   7   10.0
1   4   6.0
2   6   10.0
3   5   4.0
4   5   3.0
5   6   10.0
6   4   NaN

The output I wanted was:

df1 =
  item  sale
0   7   10.0
1   4   4.0
2   6   10.0
3   5   3.0
4   5   3.0
5   6   10.0
6   4   4.0

The two dataframes are related by item number. So, set the item number as the index on both dataframes, run an update method on df1 with df2, and reset index

df1 = df1.set_index("item")
df1.update(df2.set_index("item"))
df1.reset_index()

    item    sale
0   7   10.0
1   4   4.0
2   6   10.0
3   5   3.0
4   5   3.0
5   6   10.0
6   4   4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM