简体   繁体   中英

rotate angles by 90 degrees pandas

I'm returning the angle at each point in time from a single point using np.arctan . The direction is crudely pictured in the compass below.

This is fine but I'm hoping to rotate the compass by 90 degrees anti-clockwise. I've included a second crude compass below to show the intended orientation.

df = pd.DataFrame({  
    'Time' : ['2021-03-27 10:46:48.100','2021-03-27 10:46:48.200','2021-03-27 10:46:48.300','2021-03-27 10:46:48.400'],        
    'id' : ['A','A','A','A'],                             
    'x' : [50.0,55.0,50.0,50.0],
    'y' : [25.0,20.0,20.0,15.0],             
    })


x = df.groupby('id')['x'].diff().fillna(0).astype(float) 
y = df.groupby('id')['y'].diff().fillna(0).astype(float) 

df['Rotation'] = np.arctan2(x, y) 
df['Alpha'] = np.degrees(df['Rotation'])

out:

                      Time id     x     y  Rotation  Alpha
0  2021-03-27 10:46:48.100  A  50.0  25.0  0.000000    0.0
1  2021-03-27 10:46:48.200  A  55.0  20.0 -0.785398  135.0
2  2021-03-27 10:46:48.300  A  50.0  20.0  3.141593  -90.0
3  2021-03-27 10:46:48.400  A  50.0  15.0 -1.570796  180.0

intended output:

                      Time id     x     y  Rotation    Alpha
0  2021-03-27 10:46:48.100  A  50.0  25.0  0.000000      0.0
1  2021-03-27 10:46:48.200  A  55.0  20.0  2.356194   -135.0
2  2021-03-27 10:46:48.300  A  50.0  20.0 -1.570796      0.0
3  2021-03-27 10:46:48.400  A  50.0  15.0  3.141593    -90.0

original orientation

               0
          -45  |  45
               | 
       -90 <---x---> 90
               | 
         -135  |  135
              180
              

Intended orientation

               90
          45   |    135
               | 
         0 <---x---> 180
               | 
         -45   |  -135
              -90
# Rotate by 90 degrees
angles = np.arctan2(x, y) + np.pi / 2

# Bring back into range -179..180
angles[angles > np.pi] -= 2 * np.pi

The angle of the first row is changed as well, but as both x and y are 0 there, the angle is not properly defined anyway, you'll need to decide what to do in this case. It could be zero'd out like this:

angles[(x==0) & (y==0)] = 0

Then set the Pandas columns as before:

df['Rotation'] = angles
df['Alpha'] = np.degrees(df['Rotation'])

                      Time id     x     y  Rotation  Alpha
0  2021-03-27 10:46:48.100  A  50.0  25.0  0.000000    0.0
1  2021-03-27 10:46:48.200  A  55.0  20.0 -2.356194 -135.0
2  2021-03-27 10:46:48.300  A  50.0  20.0  0.000000    0.0
3  2021-03-27 10:46:48.400  A  50.0  15.0 -1.570796  -90.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM