【问题标题】:Looping over a list of filenames and appending them together in Python循环遍历文件名列表并将它们附加到 Python 中
【发布时间】:2016-01-28 19:43:32
【问题描述】:

到目前为止,我有一个以文件名的相同部分开头的文件列表,所以我想使用通配符并获取目录中以文件名的相同部分开头的所有文件名的列表,然后追加所有将文件放在一起,使其只是一个大文件。我知道我需要导入 glob。这就是我到目前为止所拥有的。

import glob

filename = glob.glob('1511**.mnd')
data_nov15_hereford = pd.DataFrame()
list = []

for i in filename:
  f_nov15_hereford = pd.read_csv(i, skiprows = 33, sep='\s+',chunksize=30)
  list.append(f_nov15_hereford)
  data_nov15_hereford = pd.concat(list)
  data_nov15_hereford = data_nov15_hereford.convert_objects(convert_numeric=True)

有没有更简单或更好的方法来做到这一点。 谢谢!

【问题讨论】:

    标签: python pandas append filenames


    【解决方案1】:
    import glob
    
    filename = glob.glob('1511**.mnd')
    data_nov15_hereford = pd.DataFrame()
    frames = []
    
    for i in filename:
        f_nov15_hereford = pd.read_csv(i, skiprows = 33, sep='\s+')
        frames.append(f_nov15_hereford)
    data_nov15_hereford = pd.concat(frames)
    data_nov15_hereford = data_nov15_hereford.convert_objects(convert_numeric=True)
    # save to csv
    data_nov15_hereford.to_csv(filename)
    

    • 不要在for-loop 内调用pd.concat()。这样做在很大程度上是浪费精力,因为

      data_nov15_hereford = pd.concat(list) 
      

      在循环的每次迭代中为data_nov15_hereford 分配一个新值。

    • 避免命名变量list,因为list 是一个内置的Python 类。将特定列表分配给 list 可能会导致稍后在 x = list(...) 等看似无害的代码中出现令人惊讶且难以发现的错误(这会引发 TypeError: 'list' object not callable 错误。)

    【讨论】:

    • 感谢您的帮助。我现在收到一个错误:TypeError: cannot concatenate a non-NDFrame object
    • 我的错误。当你使用chunksize=30 时,pd.read_csv 返回一个迭代器,它产生 DataFrame,而不是 DataFrame 本身。由于 pd.concat 需要一个 DataFrame 列表,因此应删除 chunksize=30
    • 好吧,这是有道理的。我想问题是我想保持 chunksize = 30 因为对于我正在循环的每个文件,我希望它每 30 行对每个文件进行一次分块(因为原始数据与标题等的外观方式)所以如果我得到摆脱它不会很好读。这有意义吗?
    • 对不起!我的错误,我摆脱了块大小,它实际上读起来很好!非常感谢,它有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多