【问题标题】:adding columns in numpy - still confused在 numpy 中添加列 - 仍然很困惑
【发布时间】:2014-02-25 02:09:59
【问题描述】:

我知道有很多关于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

【问题讨论】:

    标签: arrays numpy jupyter-notebook


    【解决方案1】:

    首先,您应该设置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.reshape(-1, 1) 显式重塑 boston.target 以具有形状 (506, 1),其中 -1 表示推断行数,以便将数据重塑为 1 列。

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

    【讨论】:

    • 所以我必须分配一个新数组来保存副本?前任。 copyarray = np.hstack((boston.data, boston.target)) 无论哪种方式,这仍然给我一个错误,这次: ValueError: all the input arrays must have the same number of dimensions
    • 我已经编辑了我的答案。您的数组 boston.target 没有形状 (506, 1)。它有不同的形状 (506,)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2018-12-22
    • 2014-07-09
    相关资源
    最近更新 更多