Skip to content
Advertisement

Return the last non-zero value in a panda df

I have a dataframe

JavaScript

The logic is if col1 is not zero, return col1. If col 1 is zero, return col2 (non-zero). If col 2 is zero, return col3. We don’t need to do anything for col4

My code looks like below but it only returns col1

JavaScript

I tried .any() and .all(), it doesnt work either. Also, is there anyway to make this piece of code more efficient?

Advertisement

Answer

A variation on @ALollz idea, since lookup is deprecated on pandas 1.2.0:

JavaScript

Output

JavaScript

UPDATE

For excluding the last column, and return 0, do this instead:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement