首页 > 解决方案 > 引用类型的 np.nditer 返回类型

问题描述

如何获得 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'>

标签: pythonnumpymatplotlibdata-science

解决方案


可能你想像这样迭代

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对象。


推荐阅读