简体   繁体   English

将多个 CSV 文件与区分大小写的列名称与 Python 组合

[英]Combining multiple CSV files with case sensitive column names with Python

I have multiple files in a folder with same column details.我在一个文件夹中有多个文件具有相同的列详细信息。 However for some of the files column name is in lower case, while for the rest column name is in upper case.但是,对于某些文件,列名是小写,而 rest 的列名是大写。

I'm using the below code to concat them in one file我正在使用下面的代码将它们连接到一个文件中

path = r'folder'
file = glob.glob(os.path.join(path, 'Add', "*.csv"))
data = pd.concat((pd.read_csv(f, sep=',', encoding='latin-1') for f in file), ignore_index=True, sort=True)
data['Period'] = '202007' #Period Column is required as string

Individual files has 40 columns, but when I'm adding all the files through 'pd.concat' I'm getting 81 columns (40 in upper case + 40 in lower case + 1 created column).单个文件有 40 列,但是当我通过“pd.concat”添加所有文件时,我得到 81 列(大写 40 + 小写 40 + 创建的 1 列)。

I need final output as 41 columns - 40 columns either in upper/lower case + 1 created column我需要最终的 output 为 41 列 - 大写/小写的 40 列 + 1 个创建的列

Thanks to Sid for the concat help.感谢 Sid 的 concat 帮助。

Update (data types): I have different data types (int, float, object) in my data.更新(数据类型):我的数据中有不同的数据类型(int、float、object)。

Try to convert your column names all to lowercase before concatenating your dataframes:在连接数据框之前,尝试将列名全部转换为小写:

df.columns = df.columns.str.lower()

You should also unify your data types.您还应该统一数据类型。 For this, have a look on astype为此,请查看astype

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM