0
$\begingroup$

Suppose I created the below data frame

data = {'Height_1': [4.3,6.7,5.4,6.2], 
        'Height_2': [5.1, 6.9, 5.1, 5.2], 
        'Height_3': [4.9,6.2,6.5,6.4]}

df = pd.DataFrame(data) 

Suppose someone comes and asks me

  1. Find the row and column of height 6.9 ?
  2. Find in how many rows and columns height 6.2 is present?

Please help me with what will be the code for this?

$\endgroup$
0
$\begingroup$

You can use pandas .isin() function to compare all the values of your dataframe to a given value:

In [10]: df[df.isin([6.9])]                                                     
Out[10]: 
   Height_1  Height_2  Height_3
0       NaN       NaN       NaN
1       NaN       6.9       NaN
2       NaN       NaN       NaN
3       NaN       NaN       NaN

Now, if you want to get rows and column directly from it use .stack() on it. So, it will be like:

In [11]: df[df.isin([6.9])].stack()                                             
Out[11]: 
1  Height_2    6.9
dtype: float64

The output is a series. This will work in case of multiple matches too where the output will be a dataframe.

$\endgroup$
2
  • $\begingroup$ Thank you ..I got my output $\endgroup$ Apr 23 '20 at 11:47
  • $\begingroup$ You may accept it as the answer if your problem got solved. $\endgroup$
    – bkshi
    Apr 23 '20 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.