Home > Back-end >  Take dataframe with column that has values from 0 to 360 and wrap around to -180 to 180
Take dataframe with column that has values from 0 to 360 and wrap around to -180 to 180

Time:09-21

I have a dataframe df with a column 'lon' that has values which range from 0 - 15 and 250 - 360. I would like to wrap the values around from -180 to 180 without a for loop. So, the input is this:

df['lon'] = [1,10,15,250,360]

and the output should look like this

df['new_lon'] = [1,10,15,-110,0]

This would be easy to do with a for loop, but I would like to do it without a loop. In particular, I don't how to deal with dataframe where I want the values less than 15 to stay the same but I want the values greater than 15 to be changed.

CodePudding user response:

Technically, you can add 180, get the modulo 360, subtract 180:

df['lon'].add(180).mod(360).sub(180)

Other approach:

df['lon'].mask(df['lon'].gt(180), df['lon'].sub(360))

In place modification:

df.loc[df['lon'].gt(180), 'lon'] -= 360

output:

0      1
1     10
2     15
3   -110
4      0
Name: lon, dtype: int64
  • Related