Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with conditional statement to pandas series

Tags:

python

pandas

This is an utterly simple question, yet, I was unable to find answer to something similar here. I've got Pandas data frame and I want to apply a function to every element in the column. So I'm making simplest possible construction:

def PolyNO(x):
if x >= 0:
    x=-0.0001086*x**3 + 0.002878*x**2 + 0.9834*x + 0.2068
else:
    x=-0.0008852*x**3 - 0.01401*x**2 + 0.9585*x + 0.08614
return x

for k in range(len(DATValues[i])):
    DATValues[k].ix[:,2]=PolyNO(DATValues[k].ix[:,2])

The program yields an answer:

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

Using all of the propositions above does not work. Where is the catch ?

like image 801
GPM Avatar asked Apr 11 '26 08:04

GPM


1 Answers

I think you can use numpy.where:

x = DATValues.ix[:,2]
print (x)
0    5
1    6
2    2
3    7
4    4
5    7
6    8
7    9
Name: c, dtype: int64

DATValues['new'] = (np.where(x >= 0, 
                   -0.0001086*x**3 + 0.002878*x**2 + 0.9834*x + 0.2068,
                   -0.0008852*x**3 - 0.01401*x**2 + 0.9585*x + 0.08614))

print (DATValues)            
        a  b  c       new
0  201603  A  5  5.182175
1  201503  A  6  6.187350
2  201403  A  2  2.184243
3  201303  A  7  7.194372
4  201603  B  4  4.179498
5  201503  B  7  7.194372
6  201403  B  8  8.202589
7  201303  B  9  9.211349   

If you need overwrite 3. column:

x = DATValues.ix[:,2]

DATValues.ix[:,2] = (np.where(x >= 0, 
                   -0.0001086*x**3 + 0.002878*x**2 + 0.9834*x + 0.2068,
                   -0.0008852*x**3 - 0.01401*x**2 + 0.9585*x + 0.08614))

print (DATValues)            
        a  b         c
0  201603  A  5.182175
1  201503  A  6.187350
2  201403  A  2.184243
3  201303  A  7.194372
4  201603  B  4.179498
5  201503  B  7.194372
6  201403  B  8.202589
7  201303  B  9.211349 
like image 177
jezrael Avatar answered Apr 12 '26 21:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!