How to Extract a Specific Column Value from a Pandas DataFrame in One of Multiple Candidates

Asked 2 years ago, Updated 2 years ago, 45 views

The following pandas DataFrames are available:

import pandas as pd
import numpy as np
df=pd.DataFrame(np.range(30).reshape(10,3), columns=pd.Index(['one', 'two', 'three')))

To get a row with a number of 22 in the two column:

df [df['two']==22]

This is easy, but
How do I get multiple rows of numbers 10 and 22 and 28 in the two column?
Thank you for your guidance.

python pandas

2022-09-30 21:45

1 Answers

You can use isin to achieve this.

In[1]:import pandas aspd                                                    
   ...: import numpy as np                                                     
   ...: df=pd.DataFrame(np.range(30).reshape(10,3), columns=pd.Index(['one', 'two', 'three')))
   ...: df
   one two three
0    0    1      2                                                             
1    3    4      5
2    6    7      8
3    9   10     11
4   12   13     14
5   15   16     17
6   18   19     20
7   21   22     23                                                             
8   24   25     26
9   27   28     29              

In[4]: df[df['two'].isin(22,25,28))]
Out [4]: 
   one two three
7   21   22     23
8   24   25     26
9   27   28     29


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.