Skip to content
Advertisement

Find ‘next’ non-null value in column

I am trying to create a new column which appends the row index of next non-null value next to the current non-null value using the following df as a starting point:

JavaScript

The output would look like this:

JavaScript

I have found a link that touches on the issue but I could not adapt to suit.. How can I get the index of next non-NaN number with series in pandas?

Thank you in advance for any help you can provide.

Advertisement

Answer

We can find the notnull values in jack. Then shift up. Then use loc to assign the results, and values to break index alignment:

JavaScript

df:

JavaScript

Explanation:

First find where the values in jack are notnull:

JavaScript

Filter to get the index there are many equivalent ways to do this:

JavaScript

Then convert to a Series so it can be shifted this will give the “next” index:

JavaScript

Then assign back to the DataFrame only where values are notnull, values is needed to break index alignment between the Series and the DataFrame:

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