i want to check last row's all value if it is non-zero,if it is non zero then give me column name.
df = pd.DataFrame({'A': [1,2,-2,0,0], 'B': [0, 0, 0, 3, -2], 'C' : [0, 0, -2, 4, 0], 'D': [0, 0, 0, 1, 0]} )
CodePudding user response:
Use:
df.columns[(df.iloc[[-1]] != 0).all()]
Output:
Index(['B'], dtype='object')
If you wish to get only column name then use:
df.columns[(df.iloc[[-1]] != 0).all()][0]
Output:
'B'
Explanation:
This line returns a boolean mask of the last row if the value is non-zero.
(df.iloc[[-1]] != 0).all()
A B C D
4 False True False False
This line applies the boolean mask to the column names of the data frame.
df.columns[]