Python 对比两个Excel文件 将两个Excel文件都有的数据存到新的Excel文件中
时间: 2024-03-15 22:45:42 浏览: 46
你可以使用 Python 的 pandas 库来实现这个功能。具体步骤如下:
1. 使用 pandas 的 read_excel 函数读取两个 Excel 文件,将它们分别存储在 DataFrame 中。
```python
import pandas as pd
df1 = pd.read_excel('file1.xlsx')
df2 = pd.read_excel('file2.xlsx')
```
2. 使用 pandas 的 merge 函数将两个 DataFrame 按照共有的列合并成一个 DataFrame。
```python
merged_df = pd.merge(df1, df2, on='共有的列名')
```
3. 使用 pandas 的 to_excel 函数将合并后的 DataFrame 存储成新的 Excel 文件。
```python
merged_df.to_excel('new_file.xlsx', index=False)
```
其中,参数 index=False 表示不将 DataFrame 的索引写入 Excel 文件中。
通过以上步骤,你就可以将两个 Excel 文件中共有的数据存储到一个新的 Excel 文件中了。
相关问题
python 比较两个excel文件匹配的列的值输出到新文件
好的,可以使用 Pandas 库来实现。下面是一个示例代码:
```python
import pandas as pd
# 读取两个 Excel 文件
df1 = pd.read_excel('file1.xlsx')
df2 = pd.read_excel('file2.xlsx')
# 指定需要匹配的列
match_columns = ['column1', 'column2']
# 比较两个文件
matched_df = pd.merge(df1, df2, on=match_columns)
# 选择需要输出的列
output_columns = ['column1', 'column2', 'column3']
# 输出匹配项到新的 Excel 文件
matched_df[output_columns].to_excel('output_file.xlsx', index=False)
```
上述代码中,`match_columns` 变量指定需要匹配的列,`output_columns` 变量指定需要输出的列。您需要将 `column1`、`column2`、`column3` 替换为您实际使用的列名。输出的匹配项将保存到名为 `output_file.xlsx` 的新 Excel 文件中。
需要注意的是,两个 Excel 文件中的匹配列中的数据类型必须相同,否则会导致比较出错。
python对比两个excel文件
可以使用Python的pandas库来对比两个Excel文件。
首先,使用pandas的read_excel函数读取两个Excel文件,并将它们存储为pandas的DataFrame对象:
```python
import pandas as pd
df1 = pd.read_excel('file1.xlsx')
df2 = pd.read_excel('file2.xlsx')
```
接下来,可以使用pandas的compare函数来比较两个DataFrame对象的差异,并将结果存储为另一个DataFrame对象:
```python
diff = pd.concat([df1, df2]).drop_duplicates(keep=False)
```
最后,可以将差异保存到一个新的Excel文件中:
```python
diff.to_excel('diff.xlsx', index=False)
```
这将创建一个名为“diff.xlsx”的新Excel文件,其中包含两个原始文件之间的差异。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)