【问题标题】:Extracting data from multiple files with python使用python从多个文件中提取数据
【发布时间】:2017-02-12 12:55:00
【问题描述】:

我正在尝试从包含 12 个 .txt 文件的目录中提取数据。每个文件包含我要提取的 3 列数据(X、Y、Z)。我想在一个 df(InforDF) 中收集所有数据,但到目前为止,我只成功地创建了一个包含所有 X、Y 和 Z 数据在同一列中的 df。这是我的代码:

import pandas as pd
import numpy as np
import os
import fnmatch

path = os.getcwd()

file_list = os.listdir(path)

InfoDF = pd.DataFrame()

for file in file_list:
    try:
        if fnmatch.fnmatch(file, '*.txt'):
            filedata = open(file, 'r')
            df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})

    except Exception as e:
        print(e)

我做错了什么?

【问题讨论】:

  • 请注意,一般情况下不要捕获异常(总是捕获特定类型的异常)
  • 每次迭代都会覆盖 df

标签: python numpy dataframe


【解决方案1】:
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})

此行在循环的每次迭代中替换 df,这就是为什么您的程序末尾只有最后一个。

您可以做的是将所有数据框保存在一个列表中并在最后连接它们

df_list = []
for file in file_list:
    try:
        if fnmatch.fnmatch(file, '*.txt'): 
            filedata = open(file, 'r')
            df_list.append(pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'}))
df = pd.concat(df_list)

或者,你可以写它:

df_list = pd.concat([pd.read_table(open(file, 'r'), delim_whitespace=True, names={'X','Y','Z'})  for file in file_list if fnmatch.fnmatch(file, '*.txt')])

【讨论】:

    【解决方案2】:

    我认为您需要glob 来选择所有文件,在list comprehension 中创建DataFrames dfs 列表,然后使用concat

    files = glob.glob('*.txt')
    dfs = [pd.read_csv(fp, delim_whitespace=True, names=['X','Y','Z']) for fp in files]
    
    df = pd.concat(dfs, ignore_index=True)
    

    【讨论】:

      【解决方案3】:
      • 正如 camilleri 上面提到的,您正在循环中覆盖 df
      • 此外,捕获一般异常也没有意义

      解决方案:在循环前创建一个空数据框InfoDF,然后使用appendconcat 填充更小的dfs

      import pandas as pd
      import numpy as np
      import os
      import fnmatch
      
      path = os.getcwd()
      
      file_list = os.listdir(path)
      
      InfoDF = pd.DataFrame(columns={'X','Y','Z'}) # create empty dataframe
      for file in file_list:
          if fnmatch.fnmatch(file, '*.txt'): 
              filedata = open(file, 'r')
              df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
              InfoDF.append(df, ignore_index=True)
      print InfoDF
      

      【讨论】:

        猜你喜欢
        • 2022-09-23
        • 2019-07-31
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        • 2013-03-13
        • 2021-03-27
        相关资源
        最近更新 更多