繁体   English   中英

从另一个数据帧中的列值替换pandas数据帧中的列中的值

[英]Replacing value in a column in pandas dataframe from a column value in another dataframe

我有两个数据帧df1df2

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看起来像

     id city
0  4735    a
1    46    b
2  2345    d
3  8768    e
4   807    f

df2看起来像:

     id city_in_mail
0  4735            x

我想将数据帧df1中列city的值从数据帧df2的列city_in_mail的值city_in_mailid值相同的行。

所以我的df1应该成为:

     id city
0  4735    x
1    46    b
2  2345    d
3  8768    e
4   807    f 

大熊猫怎么做?

使用索引来匹配,然后loc

df1 = df1.set_index('id')
df2 = df2.set_index('id')
df1.loc[df1.index.isin(df2.index), :] = df2.city_in_mail

或者使用update

c = df1.city
c.update(df2.city_in_mail)
df1['city'] = c

所有输出

        city
id  
4735    x
46      b
2345    d
8768    e
807     f

当然,最后可以自由地做df1.reset_index()以回到之前的结构。

使用与.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

尝试使用combine_first rename以对齐列索引:

df2.set_index('id')\
   .rename(columns={'city_in_mail':'city'})\
   .combine_first(df1.set_index('id'))\
   .reset_index()

输出:

       id city
0  4735.0    x
1    46.0    b
2  2345.0    d
3  8768.0    e
4   807.0    f

注意:如果您愿意,可以将其重新分配给df1。

另外.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.

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