[英]Replacing value in a column in pandas dataframe from a column value in another dataframe
I have two dataframes df1
and df2
我有两个数据帧
df1
和df2
s = {'id': [4735,46,2345,8768,807],'city': ['a', 'b', 'd', 'e', 'f']}
s1 = {'id': [4735],'city_in_mail': ['x']}
df1 = pd.DataFrame(s)
df2 = pd.DataFrame(s1)
df1
looks like df1
看起来像
id city
0 4735 a
1 46 b
2 2345 d
3 8768 e
4 807 f
and df2
looks like: 和
df2
看起来像:
id city_in_mail
0 4735 x
I want to replace the value of column city
in dataframe df1
from the value of column city_in_mail
from dataframe df2
for the row where the id
value is same. 我想将数据帧
df1
中列city
的值从数据帧df2
的列city_in_mail
的值city_in_mail
为id
值相同的行。
So my df1 should become: 所以我的df1应该成为:
id city
0 4735 x
1 46 b
2 2345 d
3 8768 e
4 807 f
How can do this with pandas ? 大熊猫怎么做?
Use indexes to match and then loc
使用索引来匹配,然后
loc
df1 = df1.set_index('id')
df2 = df2.set_index('id')
df1.loc[df1.index.isin(df2.index), :] = df2.city_in_mail
c = df1.city
c.update(df2.city_in_mail)
df1['city'] = c
All outputs 所有输出
city
id
4735 x
46 b
2345 d
8768 e
807 f
Of course, feel free to do df1.reset_index()
in the end to go back to previous structure. 当然,最后可以自由地做
df1.reset_index()
以回到之前的结构。
Using merge
with .loc
使用与
.loc
merge
s=df1.merge(df2,how='outer')
s.loc[s.city_in_mail.notnull(),'city']=s.city_in_mail
s
city id city_in_mail
0 x 4735 x
1 b 46 NaN
2 d 2345 NaN
3 e 8768 NaN
4 f 807 NaN
Try combine_first
with rename
to align column index: 尝试使用
combine_first
rename
以对齐列索引:
df2.set_index('id')\
.rename(columns={'city_in_mail':'city'})\
.combine_first(df1.set_index('id'))\
.reset_index()
Output: 输出:
id city
0 4735.0 x
1 46.0 b
2 2345.0 d
3 8768.0 e
4 807.0 f
Note: You can reassign this back to df1 if you choose. 注意:如果您愿意,可以将其重新分配给df1。
Also .map
+ .fillna
(if 'id'
is a unique key in df2
) 另外
.map
+ .fillna
(如果'id'
是df2
的唯一键)
df1['city'] = df1.id.map(df2.set_index('id').city_in_mail).fillna(df1.city)
print(df1)
# id city
#0 4735 x
#1 46 b
#2 2345 d
#3 8768 e
#4 807 f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.