【问题标题】:Generate 1d array form txt file using python使用python从txt文件生成一维数组
【发布时间】:2019-02-14 02:45:58
【问题描述】:

我是python新手。对于我的拼贴项目需要开发一些程序,为了数据分析,我使用大量数组,这些数组的值取自文本文件在txt文件中,值如下给出

0
0
0
0,0,0
0,0,0,0,0,0
0,0
0,0,0

我想转换为一维数组,例如 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

我是怎么做到的。谢谢

我得到了一些帮助完整的代码,但它不起作用,我得到一些我无法识别的错误

path2='page_2.txt'
input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=','))

错误:

ValueError                                Traceback (most recent call
last) <ipython-input-139-8836e57e833d> in <module>
      5 
      6 path2='page_2.txt'
----> 7 input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=','))
      8 
      9 path3='page_4.txt'

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname,
dtype, comments, delimiter, converters, skiprows, usecols, unpack,
ndmin, encoding)    1099         # converting the data    1100        
X = None
-> 1101 for x in read_data(_loadtxt_chunksize):1102 if X is None:1103 X = np.array(x, dtype) 
~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in
read_data(chunk_size)    1023                 line_num = i + skiprows
+ 1 1024 raise ValueError("Wrong number of columns at line %d"
-> 1025 % line_num)1026 1027# Convert each value according to its column and store

ValueError:第 4 行的列数错误

【问题讨论】:

    标签: python numpy multidimensional-array


    【解决方案1】:

    这是因为第 4 行(即 0,0,0)有三列,而不是前三行。

    您可以做的是将所有行连接起来并将其转换为一个数组:

    with open(path2) as f:
        str_arr = ','.join([l.strip() for l in f])
    
    int_arr = np.asarray(str_arr.split(','), dtype=int)
    
    print(int_arr)
    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,您希望整个文件中的所有元素都放在一个数组中。

      可以这样做:

      with open(filename) as f:
          numbers = [
              e
              for line in f
              for e in line.strip().split(',')]
      
      int_arr = np.asarray(numbers, dtype=int)
      

      之后我们有:

      >>> print(int_arr)
      array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-15
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多