[英]how to remove last column of an array in python
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.我建议您阅读有关基本切片和索引
numpy
数组的文档。
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.注 1:切片操作的结果数组
arr
只是原始数组a
内部的一个视图,没有创建副本。 If you change any entity inside the arr
, this change will also be propagated in the array a
and vice-a-versa.如果您更改
arr
任何实体,此更改也将在数组a
传播,反之亦然。
For Example, Changing the value of arr[0, 0]
will also change the corresponding value of a[0, 0]
.例如,改变
arr[0, 0]
的值也会改变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.注意 2:如果要创建一个新数组,同时删除最后一列以便一个数组中的更改不应该在另一个数组中传播,则可以使用
numpy.delete
返回一个新数组,其中子数组沿删除的轴.
arr = np.delete(a, -1, axis=1) # --> returns new array
Output of >>> arr
: >>> 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'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.