pandas isin
时间: 2023-08-21 16:07:10 浏览: 86
pandas
The `isin()` function in the pandas library is used to filter a DataFrame or Series based on whether its elements are contained in a specified set or list. It returns a boolean mask indicating whether each element is in the specified set or list.
Here's an example of how you can use `isin()`:
```python
import pandas as pd
# create a DataFrame
data = {'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e']}
df = pd.DataFrame(data)
# filter the DataFrame based on values in col1
filtered_df = df[df['col1'].isin([2, 4])]
print(filtered_df)
```
Output:
```
col1 col2
1 2 b
3 4 d
```
In this example, `isin([2, 4])` filters the rows in the DataFrame where the values in `col1` are either 2 or 4. The resulting DataFrame (`filtered_df`) contains only the rows with those values.
阅读全文