Skip to content
Advertisement

Pandas array filter NaN and keep the first value in group

I have the following pandas dataframe. There are many NaN but there are lots of NaN value (I skipped the NaN value to make it look shorter).

JavaScript

I would like to filter all the NaN value and also only keep the first value out of the NaN (e.g. from index 27-29 there are three values, I would like to keep the value indexed 27 and skip the 28 and 29 value). The targeted array should be as follows:

JavaScript

I am not sure how could I keep only the first value. Thanks in advance.

Advertisement

Answer

Take only values that aren’t nan, but the value before them is nan:

JavaScript

Output:

JavaScript

Assuming all values are greater than 0, we could also do:

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