Return the column name(s) for a specific value in a pandas dataframe

后端 未结 4 1353
孤独总比滥情好
孤独总比滥情好 2020-12-08 23:40

where I have found this option in other languages such as R or SQL but I am not quite sure how to go about this in Pandas.

So I have a file with 1262 columns and 1 r

4条回答
  •  无人及你
    2020-12-08 23:55

    Let's say we have this df . Checking only the first three rows of the df we want to get the name of the column where the specific value is 5.

    df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
        df.head(3)
    

    We can do this:

    In[61]:
    for index, row in df[:3].iterrows():
        for i in range(len(df.columns)): 
            if row[i] == 5:
                print(row.index[i])
    Out[61]:
    'D'   
    

提交回复
热议问题