【问题标题】:Splitting line and adding numbers to a numpy array分割线并将数字添加到numpy数组
【发布时间】:2016-07-28 18:46:08
【问题描述】:

我在一个文件夹中有几个文本文件,所有的数据都是数字形式的,每个都用 3 个空格分隔。没有换行符。我想取这些数字,将它们按顺序放入一个 numpy 数组中,然后将其重塑为 240 x 240 数组。 (我在每个文件中都有正确数量的数据点来执行此操作。)之后,我希望它以图形方式显示我的数组,然后对下一个文件执行相同的操作。但是,我的尝试不断给出我的错误:

"'unicodeescape' codec can't decode bytes in position 10-11: malformed \N character escape." 

到目前为止我的代码是:

import numpy as np
import matplotlib.pyplot as plt
a = np.array([])
import glob, os
os.chdir("/mydirectory")
for file in glob.glob("*.txt"):
    for line in file:
        numbers = line.split('   ')
        for number in numbers:
            a.np.append([number])
    b = a.reshape(240,240)
    plt.imshow(b)
    a = np.array([])

【问题讨论】:

  • 你看过 numpy.loadtxt 吗?

标签: python arrays python-3.x numpy


【解决方案1】:

这听起来像是读取其中一个文件的数字。我建议先做一个

 lines = file.readlines()

并确保线条看起来正确。您可能还想添加strip

In [244]: [int(x) for x in '121  342  123\n'.strip().split('  ')]
Out[244]: [121, 342, 123]

但是这种循环结构也很糟糕。这是对np.append的滥用

a = np.array([])
....
for number in numbers:
    a.np.append([number])

In [245]: a=np.array([])
In [246]: a.np.append(['123'])
...
AttributeError: 'numpy.ndarray' object has no attribute 'np'

In [247]: a.append(['123'])
...
AttributeError: 'numpy.ndarray' object has no attribute 'append'

In [248]: np.append(a,['123'])
Out[248]: 
array(['123'], 
      dtype='<U32')
In [249]: a
Out[249]: array([], dtype=float64)

np.append 返回一个新数组;它不会就地更改a

您想收集列表(或列表列表)中的值,或者至少将整数列表传递给np.array

In [250]: np.array([int(x) for x in '121  342  123\n'.strip().split('  ')])
Out[250]: array([121, 342, 123])

【讨论】:

  • 谢谢。这非常有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 2011-04-22
  • 2011-02-10
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
相关资源
最近更新 更多