且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在使用 Pandas 读取多个文件时重命名列

更新时间:2023-11-22 23:02:34

如果您想保留读取的第一个文件的列,您可以执行以下操作,存储第一次迭代的列并将该列分配给其余文件:

If you want to retain the columns of the first file which is read you can do something like this which stores the columns of the first iteration and assigns the column to the rest of the files:

dfs = []       
for e,f in enumerate(files):
    df = pd.read_excel(f)
    print(df.columns)
    if e == 0:
        col = df.columns
    df.columns=col
    dfs.append(df)


Index(['person_ID', 'Test_CODE', 'REGISTRATION_DATE', 'subject_CD',
       'subject_DESCRIPTION', 'subject_TYPE'],
      dtype='object')
Index(['person_ID', 'Test_CODE', 'REGISTRATION_DATE', 'subject_Code',
       'subject_DESCRIPTION', 'subject_Indicator'],
      dtype='object')


[df.columns for df in dfs] #pd.concat(dfs)

[Index(['person_ID', 'Test_CODE', 'REGISTRATION_DATE', 'subject_CD',
        'subject_DESCRIPTION', 'subject_TYPE'],
       dtype='object'),
 Index(['person_ID', 'Test_CODE', 'REGISTRATION_DATE', 'subject_CD',
        'subject_DESCRIPTION', 'subject_TYPE'],
       dtype='object')]