python 2.7 - Get row-index of the last non-NaN value in each column of a pandas data frame -
how can return row index location of last non-nan value each column of pandas data frame , return locations pandas dataframe?
use notnull
, idxmax
index values of non nan
values
in [22]: df = pd.dataframe({'a':[0,1,2,nan], 'b':[nan, 1,nan, 3]}) df out[22]: b 0 0 nan 1 1 1 2 2 nan 3 nan 3 in [29]: df[pd.notnull(df)].idxmax() out[29]: 2 b 3 dtype: int64
edit
actually correctly pointed out @caleb can use last_valid_index
designed this:
in [3]: df = pd.dataframe({'a':[3,1,2,np.nan], 'b':[np.nan, 1,np.nan, -1]}) df out[3]: b 0 3 nan 1 1 1 2 2 nan 3 nan -1 in [6]: df.apply(pd.series.last_valid_index) out[6]: 2 b 3 dtype: int64
Comments
Post a Comment