user7852656 user7852656 - 4 months ago 22
Python Question

How to remove elements from a list by index

I am a python beginner. The data I am given in a text file(.txt) that contains my x and y values. x and y values are tab separated.

(x values) (y values)
113 0
116 2
119 0
214 3
220 0
230 3
290 5


My task is to remove x and y values when y value is 0.

import numpy as np

files = ['my_data.txt']

for file in files:
data = np.loadtxt(file,unpack=True)


y_value = data[1,0:]

y_list= list(y_value)

a= np.where(y_list==0)
b = str(a)
d= del.y_list(b)


What I attempted to do was to identify the indexes that contains zero and remove those elements based on indices. The given code doesn't seem to work. The error message says d= del.y_list(b) contains invalid syntax.

Could someone please explain what is going wrong with d= del.y_list(b)? Or alternatively, please feel free to share any other more efficient ways to accomplish the task.

(The code above describes removing zero elements from y only. I thought that if this works for y values I could recall x values using data[0,0:].)

Thanks!

Answer Source

The compiler says that:

del.y_list(b)

Is invalid syntax. Usually one writes:

del variable
del variable[index]
del variable.attribute

To delete a variable, index, or attribute of that variable. Nevertheless I don't get why you make it that hard. You can simply write:

import numpy as np

files = ['my_data.txt']

for file in files:
    data = np.loadtxt(file,unpack=True)
    data_filtered = data[:,data[1,:] != 0]

Now data_filtered will contain a numpy matrix with only the rows where y is not equal to zero. This will be efficient and furthermore you can still perform all kinds of operations on that matrix since it is a numpy matrix.

For your sample input this generates:

>>> data[:,data[1,:] != 0]
array([[ 116.,  214.,  230.,  290.],
       [   2.,    3.,    3.,    5.]])