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

编程入门 行业动态 更新时间:2024-10-24 01:48:42
本文介绍了如何在使用 Pandas 读取多个文件时重命名列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数据框(用于 excel 文件),其中包含以下列

I have two data frames (to excel files) with the below columns

文件 1- 列

person_ID Test_CODE REGISTRATION_DATE subject_CD subject_DESCRIPTION subject_TYPE

文件 2 列

person_ID Test_CODE REGISTRATION_DATE subject_Code subject_DESCRIPTION subject_Indicator

但是,subject_CD 和 subject_Code 列的含义相同.同样,subject_TYPE 和 subject_Indicator 的意思是一样的.所以,我想在阅读excel文件时重命名它们

However, the columns subject_CD and subject_Code mean the same. Similarly, subject_TYPE and subject_Indicator mean the same. So, I would like to rename them when I read the excel file

我尝试了下面的方法,但没有用

I tried the below but it doesn't work

dfs = [] for f in files: df = pd.read_excel(f, sep=",",low_memory=False) print(df.columns) df1 = df[df.columns.intersection(['person_ID','Test_CODE','REGISTRATION_DATE','subject_CD','subject_DESCRIPTION','subject_TYPE'])].rename(columns={'subject_TYPE':'subject_Indicator','subject_CD':'subject_Code'}) dfs.append(df1)

因为我想追加/合并这两个文件,所以我希望最终数据框中的列名如下所示

Since, I would like to append/merge both the files, I expect the column names in my final data frame to be like as shown below

person_ID Test_CODE REGISTRATION_DATE subject_Code subject_DESCRIPTION subject_Indicator

可以帮我解决这个问题吗?

Can help me with this?

推荐答案

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

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')]

更多推荐

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

本文发布于:2023-10-16 16:09:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   重命名   文件   如何在   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!