过去一小时一直困扰着这一点,并且无法在这里找到适用的帖子..
假设有一个数据帧:
sample_id | value
0 NAN
1 NAN
2 NAN
3 NAN
...
19990 NAN
我有许多其他数据帧,它们是上面非常小的子集。例如:
sample_id | value
0 2
1 4
和
sample_id | value
194 2
200 4
如何使用第二个数据框更新第一个数据框中的值,但保持其他所有内容不变?使用map()会覆盖这些值,以便后续更新删除以前写入的值..
预期结果:
df = df。(df2) df = df。(df3)
最终df:
sample_id | value
0 2
1 4
..
194 2
200 4
..
19990 NAN
我知道我可以使用循环,但我确信这是一个更快的解决方案,即将在我看来没有想到的边缘......
谢谢! :)
答案 0 :(得分:1)
使用combine_first
df = pd.DataFrame({'Sample_id':pd.np.arange(0,10000),'value':pd.np.nan})
df1 = pd.DataFrame({'Sample_id':[3,4],'value':[2,4]})
df.set_index('Sample_id', inplace=True)
df1.set_index('Sample_id', inplace=True)
df_out = df1.combine_first(df)
print(df_out.head(10)
输出:
value
Sample_id
0 NaN
1 NaN
2 NaN
3 2.0
4 4.0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN