【问题标题】:How to concatenate a list of csv dataframe by for loop如何通过for循环连接csv数据框列表
【发布时间】:2021-07-28 09:57:47
【问题描述】:

我有多个 csv 文件,我正在尝试为文件夹中的所有 csv 文件连接所需的列。

这是我的代码:

import pandas as pd
import numpy as np
import os

path_dataset = r"C:\Users\KL"


def get_file(path_dataset):
    files = os.listdir(path_dataset)
    files.sort()
    file_list = []
    for file in files:
        path = path_dataset + "\\" + file

        if (file.startswith("OS")) and (file.endswith(".csv")):
            file_list.append(path)

    return file_list


read_columns = ["LX", "LY", "LZ", "LA"]

read_files = get_file(path_dataset)

for file in read_files:
    df = pd.read_csv(file, usecols=read_columns)
    all_df = [df]

Concat_table = pd.concat(all_df, axis=0)
Concat_table = Concat_table.sort_values(["LX", "LY", "LZ", "LA"])

Concat_table.to_csv(os.path.join(path_dataset, "Concate_all.csv"), index=False)

我只能读取一个文件,但不能读取所有 csv 文件。我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: python pandas dataframe concatenation


    【解决方案1】:

    您应该在阅读它们时初始化每个 DataFrame 并将其附加到 all_df 列表中,然后连接该列表。这与您在 get_file 函数中所做的相同。

    all_df = []
    for file in read_files:
        df = pd.read_csv(file, usecols=read_columns)
        all_df.append(df)
    
    Concat_table = pd.concat(all_df)
    

    【讨论】:

    • 非常感谢亚历克斯!
    猜你喜欢
    • 2020-07-01
    • 2021-12-13
    • 2020-04-25
    • 2019-12-26
    • 2019-03-02
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2019-07-20
    相关资源
    最近更新 更多