Python np.nditer引用类型的返回类型
如何为np.nditer获取正确的返回类型?我需要在这里遍历Python np.nditer引用类型的返回类型,python,numpy,matplotlib,data-science,Python,Numpy,Matplotlib,Data Science,如何为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
对象:
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'>
像这样使用
numpy
函数的问题是,它会立即将iterable转换为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
复杂性和开销是没有意义的。正确的方法是
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)
它较短,并且总是使
元素成为matplotlib.axes.\u subPlot.AxesSubplot
对象。nditer
是一个专门的迭代器,大多数numpy
工作都不需要它。正如您所发现的,它生成数组(单个元素0d)elem.item()
可能是ax[0,0]
。但是被接受的答案使用的ax.flat
是一个更好的迭代器。