Reputation: 87
I want to get an answer for c where c is defined as:
c= x+y
I have the following entry for x and y:
x y
-2 5
-3 10
2 15
4 20
6 25
to get the data, I loaded it from a csv file:
data=np.loadtxt('data.csv',delimiter=',',skiprows=1)
x_value= data[:,0]
y_value= data[:,1]
The code works fine until I decided to remove the negative entry for x. I have:
x_value1= [x for x in x_value if float(x)>0]
It now returns an error. I understand that for it to work, I also have to remove 5 and 10 in y since the entries for the equation are not the same. I don't have any idea how should I do it.
Upvotes: 0
Views: 46
Reputation: 12563
Probably you can try something like:
data[data[:,0]>0]
as hinted in the similar answer:filtering lines in a numpy array according to values in a range
Upvotes: 1
Reputation: 2133
Use your logic on data
instead, checking for negative on the first entry of each 2-tuple:
>>> data
array([[-2, 5],
[-3, 10],
[ 2, 15],
[ 4, 20],
[ 6, 25]])
>>> data2 = n.array([x for x in data if float(x[0])>0]) # x here is each row
>>> data2
array([[ 2, 15],
[ 4, 20],
[ 6, 25]])
Upvotes: 1
Reputation: 6935
You're probably going to want to ditch the list comprehension for this, since it's a longer operation and it will involve multiple lists. You could just use indices, and copy the non-negative data into new lists:
new_x = []
new_y = []
for i in range(len(x)):
if x[i] >= 0:
new_x.append(x[i])
new_y.append(y[i])
Alternate strategy using zip
:
new_x = []
new_y = []
for x_elem, y_elem in zip(x,y):
if x_elem >= 0:
new_x.append(x_elem)
new_y.append(y_elem)
I'm not sure if there's a more condensed way of doing this, but I prefer longer, more readable code anyway.
Upvotes: 1