我有两个数据框。在两个 DataFrame 中,键都有重复项,我对此表示同意。我希望目标 DataFrame 中的产品列更新为第一个 DataFrame 中的产品值。当我使用
.update()
时,由于重复值而出现错误。这可以通过某种方式一步完成吗?
我希望目标 df 中的产品与源 df 中的产品相匹配。换句话说,我想使用源来更新目标文件。与密钥关联的产品确实会随着时间的推移而改变,因此需要努力更新目标。
我希望有所帮助 - 很乐意提供更多详细信息!
import pandas as pd
source = {
"Employee ID": [123, 456, 456, 123],
"Product": ['abc', 'def', 'def', 'abc']}
target = {
"Employee ID": [123, 456, 456, 123],
"Product": ['jkl', 'mno', 'pqr', 'stu']}
target_transformed = {
"Employee ID": [123, 456, 456, 123],
"Product": ['abc', 'def', 'def', 'abc']}
source_df = pd.DataFrame(source)
target_df = pd.DataFrame(target)
result = pd.DataFrame(target_transformed)
result
你可以使用 np.where:
import numpy as np
target_df['Product']=np.where(target_df['Employee ID']==source_df['Employee ID'],source_df['Product'],target_df['Product'])