0

I have a python dataframe which contains measurements, including positions.

I need to calculate the angle of the direction, which is done by ATAN(Y/X).

However, I need to add the condition of the sign of X and Y to account for the direction of the angle (which quadrant we are in).

So, I want to know how I can run through every row in the dataframe and for the column 'X'and 'Y' I need to : If X is positive and Y is positive then.. If X is positive and Y is negative then.. If X is negative and Y is positive then.. If X is negative and Y is negative then..

I am struggling being able to apply this logic to a dataframe.

Anyone got an idea of how to solve this problem?

2 Answers 2

2

Even easier is to use np.arctan2. This will take into account the sign of your two sides to give you an angle in [-pi, pi].


To answer your actual question, you can use a nested if statements for instance:

if x >= 0:
     if y >= 0:
         # code
     else:  # y < 0
         # code
else:  # x < 0
     if y >= 0:
         # code
     else:  # y < 0
         # code
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of including such logic manually, you might want to consider using the arctan2 function from numpy; you can find the documentation here. It handles the sign of the coordinates passed to it automatically.

In this case, assuming your columns in the DataFrame are named X and Y and the DataFrame is itself named df, you could just do np.arctan2(df['Y'], df['X']).

1 Comment

Yes, such an elegant and easy solution! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.