Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: merge lists or data frames and overwrite missing values

Assuming I have the following lists:

list1 = ['MI', '', 'NY', '', 'AR', '']
list2 = ['', 'MS', '', 'OH', '', '']

Anywhere there is a missing value or an empty string in list1, I want to overwrite the empty string with a corresponding value in list2. Is there an efficient way to do this without having to iterate through each item in list1? Below is my current solution:

list1 = ['MI', '', 'NY', '', 'AR', '']
list2 = ['', 'MS', '', 'OH', '', '']

counter = 0

for each in list1:
    counter = counter + 1
    if len(each) == 0:
        list1[counter-1] = list2[counter-1]
print(list1)
>>> ['MI', 'MS', 'NY', 'OH', 'AR', '']

I tried to convert my lists to pandas data frames and used pandas.DataFrame.update() but didn't get the result I was looking for. A similar problem is solved here but in R.

like image 824
sedeh Avatar asked Oct 21 '25 02:10

sedeh


1 Answers

There's a more 'Pythonic' way to do it (using list comprehensions), but you still get an iteration in the end:

[x or y for x, y in zip(list1, list2)]
like image 125
xbug Avatar answered Oct 22 '25 16:10

xbug