Source From Here
Question
How can I achieve the equivalents of SQL's IN and NOT IN? I have a list with the required values. Here's the scenario:
My current way of doing this is as follows:
How-To
You can use pd.Series.isin:
As an example:
Question
How can I achieve the equivalents of SQL's IN and NOT IN? I have a list with the required values. Here's the scenario:
My current way of doing this is as follows:
- rows = []
- for ri, row in df.iterrows():
- if row.countries in countries:
- rows.append(ri)
- print(df.loc[rows])
You can use pd.Series.isin:
As an example:
- >>> df.head()
- countries population
- 0 US 100
- 1 UK 200
- 2 Germany 300
- 3 China 400
- >>> countries
- ['UK', 'China']
- >>> df[df.countries.isin(countries)]
- countries population
- 1 UK 200
- 3 China 400
- >>> df[~df.countries.isin(countries)]
- countries population
- 0 US 100
- 2 Germany 300
沒有留言:
張貼留言