根据另一列在pandas列中指定值

时间:2018-03-30 10:14:50

标签: python pandas replace merge

我有两个数据帧,如下所示:

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

1 个答案:

答案 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