Skip to main content
 首页 » 编程设计

Python之Pandas 合并多个文件的部分

2024年10月17日8davidwang456

在一个文件夹中列出 200 个左右的文件。每个都有相同数量的列,但命名可能有所不同。例如,我可以有 Global ID 或 Global id 或 Global Id。有没有办法控制 pandas 列名中的大小写,这样它等于什么并不重要?目前它将通过 200 个文件中的前 15 个左右的文件并会出错,因为它没有找到全局 ID。

请注意,我是初学者,仍在学习中。

import pandas as pd 
import glob 
 
with open('test99.txt' , 'a') as out: 
    list_of_files = glob.glob('M:\AD HOC Docs\Client\Blinded\*') 
    for file_name in list_of_files: 
        df = pd.read_table(file_name, low_memory=False) 
        df['Client'] = file_name.split("_")[2].strip() 
        Final = df[['Client','ClientID','Global ID','Internal ID','campaign type','engagement type', 'file_name']] 
        Final.to_csv(out,index=False) 

请您参考如下方法:

使用 header=None, names=[list of column names you want to use] 作为 read_table 的附加参数来忽略标题行并获得一致的名称。