python - Pandas 使用cols 并从多个数据帧追加
问题描述
我不确定实现这一目标的完美方法是什么:
我有多个 xlsx 文件,并且 customer_id 列在每个文件中都有不同的名称。假设以下示例:
xlsx1: customer_id
xlsx2: ID
slsx3: client_ID
xlsx4: cus_id
xlsx5: consumer_number
xlsx6: customer_number
...etc
我想读取文件夹中的所有 xlsx,然后只需提取客户 ID 列并将它们附加到一个数据帧。
到目前为止我做了什么:
我为 xlsx 文件中的每个预期 customer_id 列创建了一个列表:
customer_id = ["ID","customer_id","consumer_number","cus_id","client_ID"]
然后我读取了文件夹中的所有 xlsx 文件:
all_data = pd.DataFrame()
for f in glob.glob("./*.xlsx"):
df = pd.read_excel(f, usecols = customer_id)
all_data = all_data.append(df,ignore_index=True)
在这里我得到了错误:
ValueError: Usecols do not match columns, columns expected but not found:
我相信 usecols 匹配每个 xlsx 文件中列表中的所有列名,而我需要在 xlsx 文件中获取与名称匹配的一列。
解决方案
一种方法是阅读完整的 excel,reindex
其中可能的 IDcustomer_id
列将为错误的名称生成 nan 列,然后dropna
是它们。为以后重命名该列concat
。也不要append
在循环中使用熊猫,append
到列表和concat
稍后,它会更快。所以你得到:
l = [] #use a list and concat later, faster than append in the loop
for f in glob.glob("./*.xlsx"):
df = pd.read_excel(f).reindex(columns=customer_id).dropna(how='all', axis=1)
df.columns = ["ID"] # to have only one column once concat
l.append(df)
all_data = pd.concat(l, ignore_index=True) # concat all data
推荐阅读
- python - 如果在语句中出现问题
- pandas - Pandas Dataframe pandas.core.groupby.generic.DataFrameGroupBy 在调用 get_group(chrLong) 时给出 KeyError 尽管 chrLong 存在于 groups.keys()
- android - 即使 setOrientation 仅设置为纵向,Android 也会变成横向
- input - 当集成到第三方应用程序时,退格键在 PrimeNG 的输入框上不起作用
- r - 如何使用两个变量最小化函数
- mysql - MySQL 8:启用 LOAD DATA LOCAL INFILE
- python - 如何查找包含在引号中的多行注释?
- python - 退出应用程序时获取closeEvent
- php - 当我将数据库表放在在线主机上时,它没有连接,但它可以与 localhost 一起使用
- amazon-web-services - AWS ECS Fargate ALB 无法验证 targetGroupArn