How can I select rows from a dataframe based on a sequence of column values?

Viewed 283

Taking the below example, if I want to select all the values in column 'WHY' which correspond to certain 'EX' values, I can use the pandas .isin() function.

However, I want to select rows based on a specific series of EX values. In the below example, I would like only rows 4-7 to be selected. How can I achieve this?

import numpy as np
import pandas as pd

x_values = [1,3,5,7,9,11,13,12,11,10,9,8,7,8,9,10,12,14,16,18]
y_values = np.arange(103,123)
df = pd.DataFrame(list(zip(x_values, y_values)), columns = ['EX', 'WHY'])

    EX  WHY
0    1  103
1    3  104
2    5  105
3    7  106
4    9  107
5   11  108
6   13  109
7   12  110
8   11  111
9   10  112
10   9  113
11   8  114
12   7  115
13   8  116
14   9  117
15  10  118
16  12  119
17  14  120
18  16  121
19  18  122 

For this dataframe,

df[df['EX'].isin([9,11,13,12])]['WHY']

gives:

4     107
5     108
6     109
7     110
8     111
10    113
14    117
16    119
0 Answers
Related