0

我知道有很多关于 中的列的问题被问到并得到了回答NumPy,但我仍然被困住了。不幸的是,np.append它对我不起作用,因为它说没有模块。

我正在使用数据集,该boston数据集的中值与主数据分开存储boston.data(形状为 (506, 13) 为boston.target(形状为 (506, 1))。我想让它成为boston.target特征(又名列)被添加到boston.data,使其形状为 (506, 14),其中boston.data[13] 为boston.target数据。

根据我看到的其他建议,我的尝试是:

np.append(boston.data, boston.target, axis=0)
print boston.data.shape

但是,这给了我一个错误:

ValueError: all the input arrays must have same number of dimensions

这样做只是np.append(boston.data, boston.target)没有给我任何回报boston.data,或者至少据我所知。

我究竟做错了什么?

编辑:

如果有人ipython打开,整个代码如下:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
boston = load_boston()

print boston.data.shape
print boston.target.shape
copyarr = np.append(boston.data, boston.target, axis=1) #changed still runs error
print copyarr.shape

at --> copyarr = np.append(boston.data, boston.target, axis=1)
ValueError: all the input arrays must have the same number of dimensions
4

1 回答 1

0

首先,您应该设置axis=1,而不是0。您正在尝试添加列,而不是行。这就是为什么 numpy 给出关于数组不同维数的错误。

import numpy as np
A = np.append(boston.data, boston.target.reshape(-1, 1), axis=1)

添加列的另一种方法是使用 hstack。

import numpy as np
A = np.hstack((boston.data, boston.target.reshape(-1, 1)))

您的问题的原因是 boston.target 具有形状(506,)。它是一个一维数组,而boston.data形状 (506, 13) 是一个二维数组。您需要boston.target显式重塑形状 (506, 1) 使用boston.target.reshape(-1, 1)where -1 表示推断行数,以便将数据重塑为 1 列。

另请注意,在这两种情况下,都会制作数组的副本,即数组 boston.data 未就地修改。这意味着附加列的结果应存储在另一个变量中,如上所示。

于 2014-02-25T02:30:45.470 回答