读取两个excel表格,选择两个表格中列名均为doc_id的两列,逐行匹配两列数据相同的所有行写入新表格中
时间: 2024-05-14 22:15:53 浏览: 10
你可以使用Python中的pandas库来实现此功能。
首先,使用pandas中的read_excel()函数读取两个Excel表格,并将结果存储在两个pandas数据框中。假设表格1的文件名为excel1.xlsx,表格2的文件名为excel2.xlsx。
```python
import pandas as pd
# 读取两个Excel表格
df1 = pd.read_excel('excel1.xlsx')
df2 = pd.read_excel('excel2.xlsx')
```
接下来,选择两个表格中列名均为doc_id的两列。假设这两列分别为doc_id1和doc_id2。
```python
# 选择两个表格中列名均为doc_id的两列
doc_id1 = df1['doc_id']
doc_id2 = df2['doc_id']
```
然后,使用pandas中的merge()函数将两列数据相同的所有行匹配,并将结果存储在一个新的pandas数据框中。
```python
# 匹配两列数据相同的所有行
result = pd.merge(df1, df2, how='inner', on='doc_id')
```
最后,将新的数据框写入新表格中。假设新表格的文件名为new_excel.xlsx。
```python
# 将新的数据框写入新表格中
result.to_excel('new_excel.xlsx', index=False)
```
完成上述步骤之后,你就可以从新的Excel表格中查看匹配的数据了。
相关问题
读取两个excel表格,选择两个表格中列名均为doc_id的两列,逐行匹配两列数据相同的所有行写入新文件
你可以使用Python中的pandas模块来读取excel表格并进行数据操作。具体步骤如下:
1. 导入pandas模块: import pandas as pd
2. 读取两个excel表格: df1 = pd.read_excel('表格1路径') df2 = pd.read_excel('表格2路径')
3. 选择两个表格中列名均为doc_id的两列: doc_id1 = df1['doc_id'] doc_id2 = df2['doc_id']
4. 将两列数据相同的所有行写入新文件: df_new = pd.merge(df1, df2, on='doc_id', how='inner') df_new.to_excel('新表格路径', index=False)
注意事项:
1. 读取excel表格需要安装openpyxl模块
2. 建议在程序中加入异常处理以避免异常情况的出现
openpyxl 模块来读取两个Excel表格,选择两个表格中列名均为doc_id的两列,逐行匹配两列数据相同的所有行写入新表格中
好的,您可以使用以下代码:
```python
import openpyxl
# 读取两个Excel表格
wb1 = openpyxl.load_workbook('excel1.xlsx')
wb2 = openpyxl.load_workbook('excel2.xlsx')
# 选择两个表格中列名均为doc_id的两列
data1_col, data2_col = None, None
for sheet in wb1:
for i, col in enumerate(sheet.iter_cols(values_only=True)):
if col[0] == 'doc_id':
data1_col = sheet[f'{openpyxl.utils.cell.column_index_from_string(col[0])}']
break
for sheet in wb2:
for i, col in enumerate(sheet.iter_cols(values_only=True)):
if col[0] == 'doc_id':
data2_col = sheet[f'{openpyxl.utils.cell.column_index_from_string(col[0])}']
break
# 逐行匹配两列数据相同的所有行写入新表格中
new_wb = openpyxl.Workbook()
new_sheet = new_wb.active
new_sheet.append(data1_col[0])
for i in range(1, data1_col.__len__()):
data1 = data1_col[i].value
for data2_col_cell in data2_col:
if data2_col_cell.value == data1:
new_sheet.append(sheet[i])
# 保存新表格
new_wb.save('new_excel.xlsx')
```
希望可以帮助到您。