【问题标题】:np.nditer return type for reference types引用类型的 np.nditer 返回类型
【发布时间】:2018-09-13 15:09:02
【问题描述】:

如何获得 np.nditer 的正确返回类型?我需要在这里遍历ax 对象:

fig, ax = plt.subplots(figsize=(16,9), ncols=3, nrows=2)
for col, elem in zip(df.columns[:-1], np.nditer(ax, flags = ['refs_ok'])):
    sns.countplot(x="CLASS", hue=col, data=df, ax=elem)

我知道我可以在这里使用 ax 数组的维度进行迭代,但我想知道我是否可以完成这项工作。基本上,ax=elem 在迭代中应该看起来像ax=ax[i][j]。但事实证明它们有不同的类型:

print(type(elem))
print(type(ax[0][0]))

返回:

<class 'numpy.ndarray'>
<class 'matplotlib.axes._subplots.AxesSubplot'>

【问题讨论】:

  • nditer 是一个专门的迭代器,大多数 numpy 工作不需要。如您所见,它生成数组(单个元素 0d)。 elem.item() 可能是 ax[0,0]。但是接受的答案使用的ax.flat 是一个更好的迭代器。

标签: python numpy matplotlib data-science


【解决方案1】:

可能你想像这样迭代

fig, ax = plt.subplots(figsize=(16,9), ncols=3, nrows=2)
for col, elem in zip(df.columns[:-1], ax.flat):
    sns.countplot(x="CLASS", hue=col, data=df, ax=elem)

它更短,并且总是使 elem 成为 matplotlib.axes._subplots.AxesSubplot 对象。

【讨论】:

    【解决方案2】:

    使用像这样的numpy 函数的问题是它会立即将可迭代对象转换为np.ndarray 对象。

    因此,您的返回值将是这个np.ndarray 对象的一部分,看看下面的例子

    In [472]: list(np.nditer([[None, None], [None, None]], flags = ['refs_ok']))
    Out[472]:
    [(array(None, dtype=object), array(None, dtype=object)),
     (array(None, dtype=object), array(None, dtype=object))]
    
    In [473]: list(np.nditer([[None, None], [None, None]], flags = ['refs_ok']))[0][0]
    Out[473]: array(None, dtype=object)
    

    如果您想要 0 维 numpy 数组中的原始项目,请使用 .tolist() 方法

    正如您现在可能知道的那样,由于您没有迭代数字类型,因此引入所有这些 numpy 复杂性和开销是没有意义的,正确的做法是 https://stackoverflow.com/a/52316861/4013571

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 2012-08-20
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多