You can use the pandas.DataFrame.apply
method along with numpy
to achieve this. Here's an example:
main.py619 chars25 lines
In this example, we start by creating a sample dataframe with some missing values. We then define a function last_non_nan
to get the last non-nan value in a row. This function simply loops over the values in the row (in reverse order), and returns the first non-nan value it encounters.
We then apply this function to each row of the dataframe using df.apply(last_non_nan, axis=1)
. This returns a pandas Series with the last non-nan value of each row.
Finally, we convert the Series to a numpy array using the to_numpy
method, and print the result.
gistlibby LogSnag