我想编写一个函数,当df1和df2的列名彼此匹配时更新df1的值。
例如:
df1:
Name | Graduated | Employed | Married
AAA 1 2 3
BBB 0 1 2
CCC 1 0 1
df2:
Answer_Code | Graduated | Employed | Married
0 No No No
1 Yes Intern Engaged
2 N/A PT Yes
3 N/A FT Divorced
最后结果:
df3:
Name | Graduated | Employed | Married
AAA Yes PT Divorced
BBB No Intern Yes
CCC Yes No NO
我想编写如下代码:
IF d1.columns = d2.columns THEN
df1.column.update(df1.column.map(df2.set_index('Answer_Code').column))
最佳答案
一种方法是利用pd.DataFrame.lookup
:
df1 = pd.DataFrame({'Name': ['AAA', 'BBB', 'CCC'],
'Graduated': [1, 0, 1],
'Employed': [2, 1, 0],
'Married': [3, 2, 1]})
df2 = pd.DataFrame({'Answer_Code': [0, 1, 2, 3],
'Graduated': ['No', 'Yes', np.nan, np.nan],
'Employed': ['No', 'Intern', 'PT', 'FT'],
'Married': ['No', 'Engaged', 'Yes', 'Divorced']})
# perform lookup on df2 using row & column labels from df1
arr = df2.set_index('Answer_Code')\
.lookup(df1.iloc[:, 1:].values.flatten(),
df1.columns[1:].tolist()*3)\
.reshape(3, -1)
# copy df1 and allocate values from arr
df3 = df1.copy()
df3.iloc[:, 1:] = arr
print(df3)
Name Graduated Employed Married
0 AAA Yes PT Divorced
1 BBB No Intern Yes
2 CCC Yes No Engaged
关于python - 当两个数据框的列名匹配时查找值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50787213/