Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Data Frame: Change Negative Polar Angles to Positive

This does not work:

df[df['angle'] < 0]] += 360

How do I solve this problem? I need to have an already existing pandas dataframe with negative and positive angles update to positive polar coordinate angles (0 to 360 degrees).

Have:

[-135, -90, -45, 180, 135, 90, 45, 0, etc... ] # polar 'angles' in degrees (with negatives)

Want:

[315, 270, 225, 180, 135, 90, 45, 0, etc... ] # polar 'angles' in degrees (positive only)

// Edit (for responses): /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

This line, df[df['angle'] < 0]] += 360, gives a type error:
"TypeError: Could not operate 360 with block values must be str, not float."

The information of the dataframe 'angle' is:
"Name: angle, dtype: in64,

The original 'brute force' solution I use is:

for i in range(len(df['angle'])):
    if df['angle'][i] < 0:
        df['angle'][i] += 360

This works, but it is slow, and gives a warning, which then tells me to look up documentation on dataframe indexing.

like image 400
John Shearer Avatar asked Jan 29 '23 01:01

John Shearer


1 Answers

Use

df['angle'] %= 360 

to convert all angles regardless of sign to the range [0-360). This will work correctly for negative degrees or for angles whose absolute value exceeds 360

examples:

-270 % 360 == 90
-675 % 360 == 45
675 % 360 == 315

if you want to handle only negative degrees (i.e. allow 450 instead of converting it to 90):

df.iloc[df.angle < 360, 'angle'] %= 360
like image 196
Haleemur Ali Avatar answered Mar 23 '23 00:03

Haleemur Ali