首页 > 解决方案 > 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 文件中获取与名称匹配的一列。

标签: pythonpython-3.xpandasdataframe

解决方案


一种方法是阅读完整的 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

推荐阅读