Numpy:np.delete 没有删除数组中的值

Numpy: np.delete is not removing values in the array

我正在使用带有 numpy 版本 1.11.3 的 Python 3.5,我遇到了一个可能难以重现的非常奇怪的问题。

我从 pd.DataFrame 加载了一个 Numpy 数组 arr1,但 np.delete 似乎不起作用:

ipdb> np.delete(arr1, 53)
array([  53,   84,  140,  220,  295,  413,  478,  558,  596,  875,  986,
       1103, 1487, 1559, 1704, 1924, 2009, 2044, 2301, 2410, 2514, 2746,
       3432, 3443, 3466, 4054, 4125, 4249, 4309, 4395, 4429, 4544, 4764,
       4787, 5208, 5299, 5340, 5447, 5680, 5899, 5977, 6254, 6256, 6276,
       6412, 6518, 6538, 6584, 6587, 6591, 6592, 6593, 6594, 6661, 6662,
       6663, 6664, 6665, 6666, 6667, 6668, 6669, 6670, 6671, 6672, 6673,
       6686, 6698, 6699, 6700, 6770, 6796, 6848, 6881, 6917, 6975, 7079,
       7121, 7188, 7402, 7510, 8200, 8217, 8479, 8569, 8759, 8925, 9152,
       9190, 9243, 9423, 9485, 9583, 9681, 9690, 9692, 9710, 9793, 9811])

ipdb> arr1.dtype
dtype('int64')

ipdb> np.delete(arr1, arr1)
array([  53,   84,  140,  220,  295,  413,  478,  558,  596,  875,  986,
       1103, 1487, 1559, 1704, 1924, 2009, 2044, 2301, 2410, 2514, 2746,
       3432, 3443, 3466, 4054, 4125, 4249, 4309, 4395, 4429, 4544, 4764,
       4787, 5208, 5299, 5340, 5447, 5680, 5899, 5977, 6254, 6256, 6276,
       6412, 6518, 6538, 6584, 6587, 6591, 6592, 6593, 6594, 6661, 6662,
       6663, 6664, 6665, 6666, 6667, 6668, 6669, 6670, 6671, 6672, 6673,
       6686, 6698, 6699, 6700, 6770, 6796, 6848, 6881, 6917, 6975, 7079,
       7121, 7188, 7402, 7510, 8200, 8217, 8479, 8569, 8759, 8925, 9152,
       9190, 9243, 9423, 9485, 9583, 9681, 9690, 9692, 9710, 9793, 9811])

但是当我在 np.arange 上调用 np.delete 时它有效:

ipdb> np.delete(np.arange(15), np.arange(13))
array([13, 14])

是否可以解释为什么会发生这种情况?

numpy.delete的第二个参数不是要删除的。它是要删除的索引(或多个索引)。看看docstring中的例子,比如这个:

In [25]: arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

In [26]: arr
Out[26]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

In [27]: np.delete(arr, 1, axis=0)
Out[27]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

该函数调用中的值 1axis=0 相结合,表示 "delete the row with index 1"。