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?
I suggest you to read the docs aboutBasic 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']]
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']]
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'''
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.