假设我有以下两个数据框:
import pandas as pd
df1 = pd.DataFrame({'ID': ['01', '02', '03', '04', '05', '06'],
'Name':['Jack','Sue', pd.np.nan,'Bob','Alice','John'],
'City':['Seattle','SF','LA','OC', pd.np.nan, pd.np.nan],
'A': [1, 2.1, pd.np.nan, 4.7, 5.6, 6.8],
'B': [.25, pd.np.nan, pd.np.nan, 4, 12.2, 14.4]})
df2 = pd.DataFrame({'id': ['03', '05', '06', '07', '08', '09'],
'Name':['Mery',pd.np.nan, pd.np.nan,'Bill','Alice','John'],
'City':['NY','DC','LA','DC', 'LA', pd.np.nan],
'A': [1, 5.6, 6.8, 4.7, 5.6, 6.8],
'C': [0.5, pd.np.nan, pd.np.nan, 5, 3.7, 6.8],
'Num_children':[2,0,0,3,2,1],
'Num_pets':[5,1,0,5,2,2]})
我想使用'id', 'Name', 'City', 'A', 'C', 'Num_children'
中的df2
和{{1}中的df1
,将ID
的列df1
更新为'id'
}作为键,这是我想要的预期输出:
df2
我的实际输出:
ID Name City A B C Num_children
0 01 Jack Seattle 1.0 0.25 NaN NaN
1 02 Sue SF 2.1 NaN NaN NaN
2 03 Mery LA 1.0 NaN 0.5 2.0
3 04 Bob OC 4.7 4.00 NaN NaN
4 05 Alice DC 5.6 12.20 NaN 0.0
5 06 John LA 6.8 14.40 NaN 0.0
6 07 Bill DC 4.7 NaN 5.0 3.0
7 08 Alice LA 5.6 NaN 3.7 2.0
8 09 John NaN 6.8 NaN 6.8 1.0
如何正确合并它们?谢谢。
答案 0 :(得分:1)
将DataFrame.combine_first
与DataFrame.set_index
一起使用,最后由DataFrame.rename_axis
与DataFrame.reset_index
获得新的索引名称:
cols_to_use = ['id', 'Name', 'City', 'A', 'C', 'Num_children']
df = (df2[cols_to_use].set_index('id')
.combine_first(df1.set_index('ID'))
.rename_axis('ID')
.reset_index())
print (df)
ID A B C City Name Num_children
0 01 1.0 0.25 NaN Seattle Jack NaN
1 02 2.1 NaN NaN SF Sue NaN
2 03 1.0 NaN 0.5 NY Mery 2.0
3 04 4.7 4.00 NaN OC Bob NaN
4 05 5.6 12.20 NaN DC Alice 0.0
5 06 6.8 14.40 NaN LA John 0.0
6 07 4.7 NaN 5.0 DC Bill 3.0
7 08 5.6 NaN 3.7 LA Alice 2.0
8 09 6.8 NaN 6.8 NaN John 1.0