我有两个数据帧,如下所示:
A
Timestamp C1 C2 C3
1 0 0 0
2 0 0 0
3 0 0 0
4 0 0 0
5 0 0 0
6 0 0 0
7 0 0 0
和 乙
Timestamp C1 C2 C3
2 0 0 0
3 v1 v2 v3
4 v4 v5 v6
7 0 0 0
我想合并两个数据集,并根据Timestamp列将A中的零替换为B中的值,并使用如下所示的新A数据帧:
Timestamp C1 C2 C3
1 0 0 0
2 0 0 0
3 v1 v2 v3
4 v4 v5 v6
5 0 0 0
6 0 0 0
7 0 0 0
答案 0 :(得分:0)
我认为需要mask
才能将0
替换为NaN
combine_first
:
#convert columns to indices if necessary
#A = A.set_index('Timestamp')
#B = B.set_index('Timestamp')
df = B.mask(B == 0).combine_first(A)
#alternative
#df = B.replace({0:np.nan}).combine_first(A)
print (df)
C1 C2 C3
Timestamp
1 0 0 0
2 0 0 0
3 v1 v2 v3
4 v4 v5 v6
5 0 0 0
6 0 0 0
7 0 0 0