从Pandas中不同dataframe中的另一个匹配列更新dataframe中的列值

2024-06-01 01:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧

 df
 city   mail
  a    satya
  b    def
  c    akash
  d    satya
  e    abc
  f    xyz
#Another Dataframe d as
 city   mail
 x      satya
 y      def
 z      akash
 u      ash

所以现在我需要从'd'中的更新值中更新df中的city,比较邮件,如果没有找到某个邮件id,它应该保持原样。所以看起来应该是

 df ### o/p should be like
 city   mail
  x    satya
  y    def
  z    akash
  x    satya  #repeated so same value should placed here
  e    abc     # not found so as it was
  f    xyz

我试过——

s = {'mail': ['satya', 'def', 'akash', 'satya', 'abc', 'xyz'],'city': ['a', 'b', 'c', 'd', 'e', 'f']}
s1 = {'mail': ['satya', 'def', 'akash', 'ash'],'city': ['x', 'y', 'z', 'u']}
df = pd.DataFrame(s)
d = pd.DataFrame(s1)
#from google i tried
df.loc[df.mail.isin(d.mail),['city']] = d['city']

#给出含铁结果

 city   mail
 x  satya
 y  def
 z  akash
 u  satya  ###this value should be for city 'x'
 e    abc
 f    xyz

我不能在'mail',how''left'上进行合并,因为在一个数据框中,我的客户较少。所以合并后,如何在合并后的数据框中映射不匹配邮件所在城市的值。

请建议。


Tags: 数据citydfsodefas邮件mail
1条回答
网友
1楼 · 发布于 2024-06-01 01:47:38

看起来您想要从d中的city值更新df中的city值。^{}函数基于索引,因此首先需要设置这个。

# Add extra columns to dataframe.
df['mobile_no'] = ['212-555-1111'] * len(df)
df['age'] = [20] * len(df)

# Update city values keyed on `mail`.
new_city = df[['mail', 'city']].set_index('mail')
new_city.update(d.set_index('mail'))
df['city'] = new_city.values

>>> df
  city   mail     mobile_no  age
0    x  satya  212-555-1111   20
1    y    def  212-555-1111   20
2    z  akash  212-555-1111   20
3    x  satya  212-555-1111   20
4    e    abc  212-555-1111   20
5    f    xyz  212-555-1111   20

相关问题 更多 >