snippetpythonCritical
Use a list of values to select rows from a Pandas dataframe
Viewed 0 times
pandaslistvaluesrowsselectdataframeusefrom
Problem
Let’s say I have the following Pandas dataframe:
I can subset based on a specific value:
But how can I subset based on a list of values? - something like this:
To get:
df = DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
df
A B
0 5 1
1 6 2
2 3 3
3 4 5I can subset based on a specific value:
x = df[df['A'] == 3]
x
A B
2 3 3But how can I subset based on a list of values? - something like this:
list_of_values = [3, 6]
y = df[df['A'] in list_of_values]To get:
A B
1 6 2
2 3 3Solution
You can use the
And to get the opposite use
isin method:In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3And to get the opposite use
~:In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5Code Snippets
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5Context
Stack Overflow Q#12096252, score: 2287
Revisions (0)
No revisions yet.