Python 筛选两个Excel的两列值分别相等的数据
时间: 2024-03-16 12:44:47 浏览: 29
可以使用 pandas 库来筛选两个 Excel 的两列值分别相等的数据。具体步骤如下:
1. 使用 pandas 的 read_excel 方法读取两个 Excel 文件,得到两个 DataFrame 对象;
```
import pandas as pd
df1 = pd.read_excel('excel1.xlsx')
df2 = pd.read_excel('excel2.xlsx')
```
2. 使用 merge 方法将两个 DataFrame 对象按照相同的列名进行合并,并设置参数 on 为相同的列名,参数 how 为 inner 表示取交集;
```
merged = pd.merge(df1, df2, on='column_name', how='inner')
```
3. 最后得到的 merged DataFrame 对象就是两个 Excel 中两列值分别相等的数据。
完整代码示例:
```
import pandas as pd
df1 = pd.read_excel('excel1.xlsx')
df2 = pd.read_excel('excel2.xlsx')
merged = pd.merge(df1, df2, on='column_name', how='inner')
print(merged)
```
其中,column_name 表示两个 Excel 中需要比较的列名。
相关问题
用python筛选excel表种两列相同的数据
可以使用 pandas 库读取 excel 表格,并使用 DataFrame 的 drop_duplicates 方法来筛选两列相同的数据。
具体实现代码如下:
```python
import pandas as pd
# 读取 excel 数据到 DataFrame 中
df = pd.read_excel('your_excel_file.xlsx')
# 筛选两列相同的数据,并返回新的 DataFrame
new_df = df.drop_duplicates(subset=['column1', 'column2'])
# 输出新的 DataFrame
print(new_df)
```
注意,在 `drop_duplicates` 方法中需要指定要筛选的列,即参数 `subset` 的值为一个列表,包含两列名字。如果还有其他列需要保留,则需要在 `subset` 中添加相应的列名。
Python中如何根据excel两列相同的值分组
要根据Excel表格中两列相同的值分组,可以使用Python中的pandas库。
以下是一个示例代码,该代码读取一个Excel文件,将其中两列相同的行分组,并打印每个分组的行:
```python
import pandas as pd
# 读取Excel文件
df = pd.read_excel('example.xlsx')
# 根据两列相同的值分组
groups = df.groupby(['列1', '列2'])
# 遍历每个分组并打印行
for name, group in groups:
print('Group:', name)
print(group)
```
在这个示例中,我们首先使用`pd.read_excel()`方法读取一个Excel文件,并将其存储在一个pandas DataFrame中。然后,我们使用`groupby()`方法将DataFrame中的行按照`列1`和`列2`两列相同的值进行分组。最后,我们遍历每个分组,并使用`print()`函数打印分组的名称和行。
你需要将代码中的`example.xlsx`替换为你自己的Excel文件名,并将`列1`和`列2`替换为你想要根据其分组的列名。
相关推荐
![py](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)