【问题标题】:How to automate loading multiple files into numpy arrays using a simple "for" loop?如何使用简单的“for”循环自动将多个文件加载到 numpy 数组中?
【发布时间】:2020-12-27 14:00:41
【问题描述】:

我通常使用 np.loadtxt cammand 加载我的数据,在大多数情况下,它只包含两列:

x0, y0 = np.loadtxt('file_0.txt', delimiter='\t', unpack=True)
x1, y1 = np.loadtxt('file_1.txt', delimiter='\t', unpack=True)
.
.
xn, yn = np.loadtxt('file_n.txt', delimiter='\t', unpack=True)

然后单独绘制每一对,这并不理想!

我想为同一目录中的所有文本文件创建一个简单的“for”循环,加载文件并将它们绘制在同一个图上。

【问题讨论】:

    标签: python numpy


    【解决方案1】:
    import os
    import matplotlib.pyplot as plt
    
    # A list of all file names that end with .txt
    myfiles = [myfile for myfile in os.listdir() if myfile.endswith(".txt")]
    
    # Create a new figure
    plt.figure()
    
    # iterate over the file names
    for myfile in myfiles:
       # load the x, y
       x, y = np.loadtxt(myfile, delimiter='\t', unpack=True)
    
       # plot the values
       plt.plot(x, y)
    
    # show the figure after iterating over all files and plotting.
    plt.show()
    
    

    【讨论】:

      【解决方案2】:

      使用以下命令加载字典中的所有文件:

      d = {}
      for i in range(n):
          d[i] = np.loadtxt('file_' + str(i) + '.txt', delimiter='\t', unpack=True)
      

      现在,要访问 kth 文件,请使用 d[k] 或:

      xk, yk = d[k]
      

      由于您没有提到文件中的数据和您要创建的绘图,所以很难说该怎么做。但是对于绘图,您可以参考MttplotlibSeaborn 库。

      【讨论】:

      • 谢谢。但是,如何加载任意名称的文件?!
      【解决方案3】:

      你也可以使用glob获取所有文件-

      from glob import glob
      import numpy as np
      import os
      
      res = []
      
      file_path = "YOUR PATH"
      file_pattern = "file_*.txt"
      
      files_list = glob(os.path.join(file_path,file_pattern))
      
      for f in files_list:
          print(f'----- Loading {f} -----')
          x, y = np.loadtxt(f, delimiter='\t', unpack=True)
          res += [(x,y)]
      

      res 将在与f 对应的每个索引值处包含您的文件内容

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2020-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        相关资源
        最近更新 更多