【问题标题】:Python appending a list in a for loop with numpy array dataPython在带有numpy数组数据的for循环中附加一个列表
【发布时间】:2015-10-05 07:20:14
【问题描述】:

我正在编写一个程序,它将附加一个列表,其中包含从二维 numpy 数组中提取的单个元素。到目前为止,我有:

# For loop to get correlation data of selected (x,y) pixel for all bands
zdata = []
for n in d.bands:
    cor_xy = np.array(d.bands[n])
    zdata.append(cor_xy[y,x])

每次我运行我的程序,我都会收到以下错误:

Traceback (most recent call last):
    File "/home/sdelgadi/scr/plot_pixel_data.py", line 36, in <module>
        cor_xy = np.array(d.bands[n])
TypeError: only integer arrays with one element can be converted to an index

当我在不使用循环的情况下从 python 解释器中尝试时,我的方法有效,即

>>> zdata = []
>>> a = np.array(d.bands[0])     
>>> zdata.append(a[y,x])
>>> a = np.array(d.bands[1])
>>> zdata.append(a[y,x])
>>> print(zdata)
[0.59056658, 0.58640128]

创建一个 for 循环并手动执行此操作有什么不同,我怎样才能让我的循环停止导致错误?

【问题讨论】:

  • d.bands 长什么样子?
  • nd.bands 的元素时,您将其视为d.bands 的索引。
  • @AnandSKumar 'd.bands' 是 50x50 二维数组的列表。

标签: python arrays python-3.x numpy typeerror


【解决方案1】:

当它是d.bands 的元素时,您将n 视为d.bands 的索引

zdata = []
for n in d.bands:
    cor_xy = np.array(n)
    zdata.append(cor_xy[y,x])

你说a = np.array(d.bands[0]) 有效。第一个n 应该与d.bands[0] 完全相同。如果是这样,那么np.array(n) 就是您所需要的。

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2019-07-12
    • 2016-07-31
    • 2018-04-17
    • 2020-12-29
    • 2017-03-23
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多