3

My array size is unknown and I would like to remove the very last column

a = np.array([["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]])

I have tried

a[-1:]

but it deleted all rows except the last row

I also tried

a[:-1]

and it deleted the last row.

How can I delete the last column?

3

3 Answers 3

11

I suggest you to read the docs about Basic Slicing and Indexing the numpy array.

Try this:

arr = a[:, :-1] #--> first two columns of array

Note 1: The resulting array arr of the slicing operation is just a view inside the original array a, no copy is created. If you change any entity inside the arr, this change will also be propagated in the array a and vice-a-versa.

For Example, Changing the value of arr[0, 0] will also change the corresponding value of a[0, 0].


Note 2: If you want to create a new array, while removing the last column so that changes in one array should not be propagated in other array, you can use numpy.delete which returns a new array with sub-arrays along an axis deleted.

arr = np.delete(a, -1, axis=1) # --> returns new array

Output of >>> arr:

[['A1' 'A2']
 ['B1' 'B2']
 ['C1' 'C2']]
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

import numpy as np
a = np.array([["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]])
print(a)

b = np.delete(a, np.s_[-1:], axis=1)
print(b)

Output:

[['A1' 'A2' 'A3']
 ['B1' 'B2' 'B3']
 ['C1' 'C2' 'C3']]

[['A1' 'A2']
 ['B1' 'B2']
 ['C1' 'C2']]

Comments

0

If you wish to delete the last column

b = a[:,:2]
'''array([['A1', 'A2'],
   ['B1', 'B2'],
   ['C1', 'C2']], dtype='<U2')'''

if you wish to delete the last row

c = a[:2]
'''array([['A1', 'A2', 'A3'],
   ['B1', 'B2', 'B3']], dtype='<U2'''

Comments

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.