簡體   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