Extracting column names of locations with specific values among Pandas data frames

Asked 2 years ago, Updated 2 years ago, 54 views

If you know a particular value in a Pandas data frame, how do you output the column name for that value?

And if you know a particular value, I wonder how to output the position of that value!

I can't find it even if I keep searching, so I'm leaving a question. Thank you.

pandas python dataframe

2022-09-20 19:30

1 Answers

>>> df = pd.DataFrame({"a":[1,2,3,1], "b":[3,3,1,1]})
>>> df
   a  b
0  1  3
1  2  3
2  3  1
3  1  1
>>> df==1
       a      b
0   True  False
1  False  False
2  False   True
3   True   True
>>> (df==1).any(axis=0)
a    True
b    True
dtype: bool
>>> df.loc[:,(df==1).any(axis=0)]
   a  b
0  1  3
1  2  3
2  3  1
3  1  1
>>> df.loc[(df==1).any(axis=1), :]
   a  b
0  1  3
2  3  1
3  1  1
>>> colnames = df.columns
>>> for idx, row in df.iterrows():
    for col in colnames:
        if row[col] == 1:
            print(idx, col)


0 a
2 b
3 a
3 b
>>> for idx, row in (df==1).iterrows():
    for col in colnames:
        if row[col]:
            print(idx, col)


0 a
2 b
3 a
3 b


2022-09-20 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.