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]} )
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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[]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0