这一个python代码,让excel中前两列自动匹配一个文件夹中所有excel前两列逐行匹配,如果匹配找到特定表头的列返回
时间: 2024-05-06 08:14:55 浏览: 13
可以使用`pandas`库来完成这个任务。以下是一个可能的解决方案:
```python
import os
import pandas as pd
# 设置文件夹路径和目标表头
folder_path = 'path/to/folder'
target_header = 'Target Header'
# 读取Excel文件夹中的所有文件
files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx')]
# 读取并匹配Excel文件中的前两列
for file in files:
df = pd.read_excel(os.path.join(folder_path, file))
match = df.iloc[:, :2].apply(tuple, axis=1).isin(df1.iloc[:, :2].apply(tuple, axis=1))
if any(match):
# 如果前两列匹配成功,则返回目标表头所在的列
target_col = df.columns[df.columns.str.contains(target_header)][0]
print(f"在文件 {file} 中找到了目标表头 {target_header},列号为 {target_col}")
```
这个代码首先读取指定文件夹中的所有Excel文件,然后逐个打开并读取它们。对于每个文件,代码使用`pandas`库的`read_excel`函数读取Excel文件,并使用`iloc`函数选择前两列。然后,代码将前两列转换为元组,并使用`isin`函数将它们与目标文件匹配。如果匹配成功,则代码使用`columns`属性查找目标表头所在的列,并打印出文件名、目标表头和列号。
请注意,这个代码假设所有Excel文件中的表头都是唯一的。如果有多个表头匹配目标表头,则这个代码将返回第一个匹配的列。如果需要,可以根据具体情况进行修改。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)