2016-06-24 19 views
0

删除列这是(3X9)阵列:如何从一个数组

[[ 0 1 2 3 4 5 6 7 8] 
    [ 9 10 11 12 13 14 15 16 17] 
    [18 19 20 21 22 23 24 25 26]] 

我想有像这样(3×3):

[[ 2 7 8] 
    [11 16 17] 
    [20 25 26]]  

我写了一些代码。 有没有更好的方法来做到这一点?

AB = x[:,2:] #Removes the first 2 columns 
    print(AB) 
    C = np.delete(AB, 1, 1) 
    print(C) 
    D = np.delete(C, 1, 1) 
    print(D) 
    E = np.delete(D, 1, 1) 
    print(E) 
    F = np.delete(E, 1, 1) 
    print(F) 

回答

1

你可以做bulk删除普通的Python,使用zipenumerate

cols_to_del = [0, 1, 3, 4, 5, 6] 
AB_trans = [v for i, v in enumerate(zip(*AB)) if i not in cols_to_del] 
AB = np.array(list(zip(*AB_trans))) 
print(AB) 
# array([[ 2, 7, 8], 
#  [11, 16, 17], 
#  [20, 25, 26]]) 

的想法是转数组,并删除列(这是如今作为行)。

+0

谢谢。我用两行代码做了它。虽然你的“聪明” – Aizzaac

2
index = [0, 1, 3, 4, 5, 6]  #Set the index of columns I want to remove 
    new_a = np.delete(x, index, 1) #x=name of array 
            #index=calls the index array 
            #1=is the axis. So the columns 
    print(new_a)     #Print desired array 
+0

是的,看起来更清洁(+1)。修复你的缩进 –