I've created vector x and I need to create a vector z by removing the 3rd and 6th elements of x. I cannot just create a vector by simply typing in the elements that should be in z. I have to index them or use a separate function.
x = [5,2,0,6,-10,12]
np.array(x)
print x
z = np.delete(x,)
I am not sure if using np.delete is best or if there is a better approach. Help?
CodePudding user response:
You can index and conact pieces of the list excluding the one you want to "delete"
x = [5,2,0,6,-10,12]
print ( x[0:2] x[3:5] )
[5, 2, 6, -10]
CodePudding user response:
You can use numpy.delete
like below:
del_idx = np.array([3,6])
# Because index start from zero, We need to pass 'del_idx-1' -> [2, 5]
x_new = np.delete(np.asarray(x), del_idx-1)
print(x_new)
Or You can define a list of indexes that you want to delete and use enumerate
in the original_list
and keep elements that the index of them doesn't exist in delete_index
.
(This approach based list_comprehensions
)
import numpy as np
del_idx = [3,6]
x = [5,2,0,6,-10,12]
x_new = [item for idx, item in enumerate(x) if (idx 1) not in del_idx]
print(np.array(x_new))
Output:
[ 5 2 6 -10]
CodePudding user response:
if x is numpy array, first convert to list:
x = list(x)
if not array then:
z = [x.pop(2), x.pop(-1)]
This will remove 3rd and 6th element form x and place it in z. Then convert it to numpy array if needed.
CodePudding user response:
In [69]: x = np.array([5,2,0,6,-10,12])
Using delete
is straight forward:
In [70]: np.delete(x,[2,5])
Out[70]: array([ 5, 2, 6, -10])
delete
is a general function that takes various approaches based on the delete object, but in a case like this it uses a boolean mask:
In [71]: mask = np.ones(x.shape, bool); mask[[2,5]] = False; mask
Out[71]: array([ True, True, False, True, True, False])
In [72]: x[mask]
Out[72]: array([ 5, 2, 6, -10])