【问题标题】:Trying to get columns while reading multiple csv files. Only getting first two columns尝试在读取多个 csv 文件时获取列。只得到前两列
【发布时间】:2023-01-12 21:48:10
【问题描述】:

我正在读取一个文件夹中的所有 csv 文件(大约 90 个文件)。每个文件大约有 85 列,我只对 2 列感兴趣,所以我试图在我的 df 中只复制这些。但是我得到的 df 只显示前两列。

csv 文件如下所示:csv file

我的代码:

csv_files = glob.glob(os.path.join("C:/User/Documents/Auswertung/2/Vent_2022/*.csv"))
frames = [pd.read_csv(file, sep=';', low_memory=False, usecols = ['LOCALTIME', 'Flow_filter'], names = ['LOCALTIME', 'Flow_filter']) for file in csv_files]
df_vent = pd.concat(frames, ignore_index = True)
df_vent.drop([0,1,2], axis=0, inplace=True)

display(df_vent)

我想要得到的是:

LOCALTIME Flow_filter
01.07.2022 00:01:00 69
24.07.2022 22:46:00 167
09.08.2022 15:14:00 38
06.09.2022 18:45:00 51

我得到了什么:

LOCALTIME Flow_filter
01.07.2022 00:01:00 01.07.2022 00:01:00
24.07.2022 22:46:00 24.07.2022 22:46:00
09.08.2022 15:14:00 09.08.2022 15:14:00
06.09.2022 18:45:00 06.09.2022 18:45:00

有人知道为什么会这样,我该如何纠正?提前致谢 :)

【问题讨论】:

    标签: python pandas dataframe csv


    【解决方案1】:

    当您将 names = ['LOCALTIME', 'Flow_filter'] 选项传递给 pd.read_csv 时,您实际上是在覆盖文件中的标题行,因此说这些是前两列的名称。然后你说选择这两列,因此选择前两列。

    由于您的文件有标题行,只需删除该选项即可让pd.read_csv 为您读取列名,然后usecols = ... 应该会按您的预期工作。

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 2021-11-26
      • 2015-07-05
      • 1970-01-01
      • 2015-07-22
      • 2020-06-11
      • 2020-06-30
      • 2017-01-26
      相关资源
      最近更新 更多