1

Please consider this data frame:

date         value      
-------------------
20201001      -100
20200202      200
20200303       0
...

I want to hav1e another very simple column: "Status"

if Value < 0 Then "Status" = -1

if Value > 0 Then "Status" = 1

if Value = 0 Then "Status" = 0

I wrote this code:

data['Status'] = (data['Value'] / math.fabs(data['Value'])) if data['Value'] != 0 else 0

but I got this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How to create this column without For loop. Thanks

Edit 1) I wrote the code this way but I got same error:

data['Status'] = (data['Value'] / math.fabs(data['Value'])) if data[data['Value'] != 0] else 0

1 Answer 1

3

Use numpy.sign:

data['Status'] = np.sign(data['Value'])

If only integers use Series.clip:

data['Status'] = data['Value'].clip(lower=-1, upper=1)

Your solution working with list comprehension:

data['Status'] = [x / math.fabs(x) if x != 0 else 0 for x in data['Value']]
print (data)
       date  value  Status
0  20201001   -100    -1.0
1  20200202    200     1.0
2  20200303      0     0.0

Performance:

#300k rows
data = pd.concat([data] * 100000, ignore_index=True)

In [72]: %timeit data['Status'] = np.sign(data['Value'])
3.2 ms ± 57.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [73]: %timeit data['Status'] = data['Value'].clip(lower=-1, upper=1)
5.99 ms ± 49.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [74]: %timeit data['Status'] = [x / math.fabs(x) if x != 0 else 0 for x in data['Value']]
144 ms ± 483 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)   
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. Is there any way without numpy?
@Arian - Then is possible use clip
thanks it works. But I want to know What's wrong with my code? Why I can't write condition that way? Thanks
@Arian - If need performance with multiple if-else best is use numpy.select, but for -1,0,1 is best np.sign here
Honestly, I wanted to know what is wrong with my code that gives an error?
|

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.