我有两个Pandas DataFrame,我想与另一个一起更新... 但是我不能确定索引是否匹配。 (因此使用 DataFrame.update !是一个问题)
例子:
import pandas as pd
df1 = pd.DataFrame([('path1', 0, 0, 0),
('path2', 0, 0, 0),
('path3', 0, 0, 0),
('path4', 0, 0, 0),],
columns=['path', 'class', 'manual', 'conf'],
index = [1,2,3,4])
df2 = pd.DataFrame([('path1', 1, 0, 0),
('path2', 0, 1, 0),
('path3', 0, 0, 1),
('path5', 1, 1, 0),
('path6', 1, 1, 0),],
columns=['path', 'class', 'manual', 'conf'],
index = [10,11,12,13,14])
理想的结果:
update_annotations(df1, df2)
path class manual conf
1 path1 1 0 0
2 path2 0 1 0
3 path3 0 0 1
4 path4 0 0 0
df1.update(df2)可能有风险,因为这些数据帧的索引可能不匹配。最安全,最有效的方法是什么?
答案 0 :(得分:4)
df1[['path']].merge(df2, 'left')
path class manual conf
0 path1 1.0 0.0 0.0
1 path2 0.0 1.0 0.0
2 path3 0.0 0.0 1.0
3 path4 NaN NaN NaN
df1[['path']].merge(df2, 'left').fillna(0).astype(df1.dtypes)
path class manual conf
0 path1 1 0 0
1 path2 0 1 0
2 path3 0 0 1
3 path4 0 0 0
用NaN
填充df1
df1[['path']].merge(df2, 'left').fillna({**df1}).astype(df1.dtypes)
path class manual conf
0 path1 1 0 0
1 path2 0 1 0
2 path3 0 0 1
3 path4 0 0 0
df1.set_index('path').assign(**df2.set_index('path')).reset_index()
path class manual conf
0 path1 1.0 0.0 0.0
1 path2 0.0 1.0 0.0
2 path3 0.0 0.0 1.0
3 path4 NaN NaN NaN
由于可以保证顺序相同,因此我们可以只使用set_index
df1[['path']].merge(df2, 'left').fillna({**df1}).astype(df1.dtypes).set_index(df1.index)
path class manual conf
1 path1 1 0 0
2 path2 0 1 0
3 path3 0 0 1
4 path4 0 0 0
答案 1 :(得分:1)
基于piRSquared的出色回答, 我一直在寻找答案:
df1 = (df1[['path']]
.merge(df2, 'left')
.set_index(df1.index)
.fillna(df1))