Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python & Pandas: How to do conditional calculation

Tags:

python

pandas

df['direction'] is the number of direction of the wind, ranging from 1-16. I want to convert it into 360-degree system. #1 direction is 90, and #2 is 67.5, they run in clockwise.

I can dodf['degree'] = 90-(df.direction-1)*22.5, but this would produce negative value, you can see the output below ![enter image description here]1

But I don't know how to use the conditional here, for df['degree']<0, then + 360. How can I do that?

like image 548
cqcn1991 Avatar asked Dec 01 '25 05:12

cqcn1991


2 Answers

df['degree'] = df['degree'].apply(lambda x: x + 360 if x < 0 else x)

like image 177
DeepSpace Avatar answered Dec 03 '25 18:12

DeepSpace


You can use .loc for conditional indexing

df.loc[ df.degree < 0 , 'degree'] += 360
like image 32
dermen Avatar answered Dec 03 '25 18:12

dermen



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!