1

I'm populating an array, reading data from file:

Input:

2
4
-8
5
-2

Code:

f = [ i.strip() for i in open('file.txt', 'r') ]
a = []

for line in f:
   line = line.split()
   a.append(float(line[0]))

that produces the vector a=[2,4,-8,5,-2]. Now I want to replace all negative values with their values +10, in order to obtain a vector b=[2,4,2,5,8]. Without using a loop or a for cycle, how can I do that? I tried both using the np.where() function and the a[a<0], but they don't produce any result (they just work if I create a np.array[2,4,-8,5,-2] ex novo...). Thank you in advance.

3
  • Why not do it in your i.strip() for... loop? Commented Feb 2, 2016 at 8:37
  • 1
    After all there'll be a loop, no matter what function you choose to use. Commented Feb 2, 2016 at 8:38
  • 3
    What would -11 become? -1 or add 10 again to get +9? Commented Feb 2, 2016 at 8:51

4 Answers 4

4

one way not using numpy

a = list(map(lambda x:x+10 if x < 0 else x, a))

Sign up to request clarification or add additional context in comments.

1 Comment

Nice to see a functional answer in here. The more Pythonic way to write this notation would be a = [x+10 if x < 0 else x for x in a]
2

You could make a a numpy array:

a = np.array(a)

and then simply do:

a[a<0] += 10

3 Comments

IN my opinion Numpy is wayyyy overkill unless you're reading a ton of values and doing performance-critical computations on them. There's a simple way of binary-filtering values in python, that's with an if-else expression.
@machineyearning But OP explicitely said "Without using a loop or a for cycle" ... One could argue though if list comprehension is actually a for loop.
In that case I'd also question whether numpy array iteration uses some kind of a loop. I had read OP as meaning he would like a way to do it with a single expression, rather than a syntax block. I digress though, OP did mention numpy, so it could actually be the case that this is a large and performance-critical set of numbers to crunch. In that case it's up to OP to choose the right answer that fits his/her needs.
2

It can be done with list comprehension without using NumPy. Assuming you have list of numbers a:

>>> a = [2, 4, -8, 5, -2]
>>> [number if number >= 0 else number + 10 for number in a]
[2, 4, 2, 5, 8]

Comments

1

If you allow the use of numpy:

import numpy as np

f = [ i.strip() for i in open('C:/Users/simon/Desktop/file.txt', 'r') ]
a = []

for line in f:
   line = line.split()
   a.append(float(line[0]))

a = np.array(a)

print a

a[a<0] = a[a<0] + 10

print a

That will give you:

[ 2.  4. -8.  5. -2.]
[ 2.  4.  2.  5.  8.]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.