how to extract common values using python
时间: 2024-04-12 17:30:27 浏览: 25
To extract common values between two lists in Python, you can use the `set` data structure and the `intersection` method. Here's an example:
```python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common_values = set(list1).intersection(list2)
print(common_values)
```
Output:
```
{3, 4}
```
In the above code, we convert `list1` and `list2` into sets using the `set()` function. Then, we use the `intersection()` method to find the common values between the two sets. The result is a new set `common_values` that contains the common elements.
If you want to extract common values between two columns in a pandas DataFrame, you can use the `intersect1d` function from the numpy library. Here's an example:
```python
import numpy as np
import pandas as pd
# Create an example DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
# Extract common values between two columns
common_values = np.intersect1d(df['A'], df['B'])
print(common_values)
```
Output:
```
[3 4]
```
In this example, we use the `intersect1d()` function from numpy to find the common values between columns `'A'` and `'B'` in the DataFrame `df`. The result is a numpy array `common_values` containing the common elements.
相关推荐
![epub](https://img-home.csdnimg.cn/images/20210720083646.png)
![mobi](https://img-home.csdnimg.cn/images/20210720083646.png)
![azw3](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)