How to find the last non zero element in every column throughout dataframe?
You can convert 0
to missing values, use forward filling and select last row by indexing, last cast to integer:
df = df.mask(df==0).ffill().iloc[[-1]].astype(int)
print (df)
A B
5 10 2
Here's one approach using ndarray.argmax
and advanced indexing:
first_max = df.values[df.ne(0).values.argmax(0), range(df.shape[1])]
out = pd.DataFrame([first_max], columns=df.columns)
df = pd.DataFrame({'A': [0,0,0,10,0,0] , 'B': [0,2,0,0,0,0]})
first_max = df.values[df.ne(0).values.argmax(0), range(df.shape[1])]
# array([10, 2])
pd.DataFrame([first_max], columns=df.columns)
A B
0 10 2
Update
In order to find the last nonzero:
row_ix = df.shape[0]-df.ne(0).values[::-1].argmax(0)-1
first_max = df.values[row_ix, range(df.shape[1])]
out = pd.DataFrame([first_max], columns=df.columns)