0

This is the (3x9) array:

    [[ 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]]

I want to have it like this (3x3):

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

I wrote some code. Is there a better way to do it?

    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)

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, looks cleaner (+1). Fix your indentation
1

You can do the bulk delete in plain python, using zip and enumerate:

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]])

The idea is to transpose the array, and delete the columns (which are now presented as rows).

1 Comment

Thank you. I did it with 2 lines of code. Although yours is "brainy"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.