is it possible to know name of column and row for specific value of a dataframe? for example i have a dataframe with name 'a' like this:
dataframe=pd.DataFrame([[0,5,2,1,3],[5,0,4,6,7],[2,4,0,8,9],[1,6,8,0,3],[3,7,9,3,0]]
, columns=["A","B","C","D","E"] , index=["A","B","C","D","E"])
and i want row name and column name of element '1' that is [A,D] and [D,A].
CodePudding user response:
@alireza - Below line will give you the row and column names and index. You can take user input, where I have put it as == 1
. Code borrowed from here
Code
[(i, np.where(dataframe[i] == 1)[0].tolist()) for i in list(dataframe) if len(np.where(dataframe[i] == 1)[0]) > 0]
Output
[('A', [3]), ('D', [0])]
CodePudding user response:
You can filter by the condition you want, and then use this previous question:
How to get row, column indices of all non-NaN items in Pandas dataframe
To get indices of all non-nan
values:
import pandas as pd
dataframe=pd.DataFrame([[0,5,2,1,3],[5,0,4,6,7],[2,4,0,8,9],[1,6,8,0,3],[3,7,9,3,0]] , columns=["A","B","C","D","E"] , index=["A","B","C","D","E"])
df_ones = dataframe[dataframe == 1]
l = list(df_ones[df_ones.notnull()].stack().index)
print(l)
CodePudding user response:
try this
def find_index_and_row(df):
result = []
for index,row in df.iterrows():
for column in df.columns:
if row[column] == 1:
result.append((index,column))
return result