繁体   English   中英

使用 Pandas 将特定列值替换为另一个数据框列值

[英]Replace specific column values with another dataframe column value using Pandas

有 2 个数据框,第一个数据框包含 3 列 emp_id、emp_name 和旧的 email_id。 而第二个数据框包含 2 列 emp_id 和新的 email_id。

任务是查找第二个数据帧并替换第一个数据帧中的某些值。

输入数据框:

import pandas as pd
data = { 
'emp_id': [111, 222, 333, 444, 555],
'emp_name': ['Sam','Joe','Jake','Rob','Matt'],
'email_id': ['one@gmail.com','two@gmail.com','three@gmail.com','four@gmail.com','five@gmail.com']
}
data = pd.DataFrame(data)

电流输出:

     emp_id  emp_name email_id
0     111    Sam      one@gmail.com
1     222    Joe      two@gmail.com
2     333    Jake     three@gmail.com
3     444    Rob      four@gmailcom
4     555    Matt     five@gmail.com

#replace certain values with new values by looking up another dataframe
data1 = { 
'emp_id': [111, 333, 555],
'email_id': ['one@yahoo.com','three@yahoo.com','five@yahoo.com']
}
data1 = pd.DataFrame(data1)

期望输出:

 data = 

     emp_id  emp_name email_id
0     111    Sam      one@yahoo.com
1     222    Joe      two@gmail.com
2     333    Jake     three@yahoo.com
3     444    Rob      four@gmailcom
4     555    Matt     five@yahoo.com

原始数据包含 50k+ 行,因此合并它们似乎不是正确的选择。 任何帮助,将不胜感激。

干杯!

让我们尝试update

out = data.set_index('emp_id')
out.update(data1.set_index('emp_id')[['email_id']])
out.reset_index(inplace=True)
out
   emp_id         email_id
0     111    one@yahoo.com
1     222    two@gmail.com
2     333  three@yahoo.com
3     444   four@gmail.com
4     555   five@yahoo.com

我将提供的解决方案使用Panda 的 Boolean Indexing

# Compare the column of interest of the DataFrames. Returns a Pandas Series with True/False based on the inequality operation.
difference = (data1['email_id'] != data2['email_id'])

# Get the indexes of the different rows, i.e the rows that hold True for the inequality.
indexes_to_be_changed = data1[difference].index

# Replace the rows of the first DataFrame with the rows of the second DataFrame.
data1.iloc[indexes_to_be_changed] = data2.iloc[indexes_to_be_changed]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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