Home > Software design >  how to compare and merge two list according to its sequence in python?
how to compare and merge two list according to its sequence in python?

Time:09-22

Let say i have two lists that is intended to be merged:

a=[0.1,0.2,'-','-',0.3]
b=['-','-',0.4,0.5,'-']

how to merge a and b to its current position to be like this?

c=[0.1,0.2,0.4,0.5,0.3]

thanks

CodePudding user response:

Assuming either a or b has a float for a given position.

One possibility:

c = [x if isinstance(x, float) else y for x,y in zip(a,b)]

output: [0.1, 0.2, 0.4, 0.5, 0.3]

Using :

pd.Series(a).replace('-', pd.NA).fillna(pd.Series(b))

output:

0    0.1
1    0.2
2    0.4
3    0.5
4    0.3
dtype: float64
  • Related