Modify 2 columns in dataframe based on condition

Viewed 92

I have seen a bunch of examples on Stack Overflow on how to modify a single column in a dataframe based on a condition, but I cannot figure out how to modify multiple columns based on a single condition.

If I have a dataframe generated based on the below code -

import random
import pandas as pd

random_events = ('SHOT', 'MISSED_SHOT', 'GOAL')
events = list()

for i in range(6):
    event = dict()
    event['event_type'] = random.choice(random_events)
    event['coords_x'] = round(random.uniform(-100, 100), 2)
    event['coords_y'] = round(random.uniform(-42.5, 42.5), 2)
    events.append(event)

df = pd.DataFrame(events)
print(df)
   coords_x  coords_y   event_type
0      4.07    -21.75         GOAL
1     -2.46    -20.99         SHOT
2     99.45    -15.09  MISSED_SHOT
3     78.17    -10.17         GOAL
4    -87.24     34.40         GOAL
5    -96.10     30.41         GOAL

What I want to accomplish is the following (in pseudo-code) on each row of the DataFrame -

if df['coords_x'] < 0:
    df['coords_x'] * -1
    df['coords_y'] * -1

Is there a way to do this via an df.apply() function that I am missing?

Thank you in advance for your help!

1 Answers

IIUC, you can do this with loc, avoiding the need for apply:

>>> df
   coords_x  coords_y   event_type
0      4.07    -21.75         GOAL
1     -2.46    -20.99         SHOT
2     99.45    -15.09  MISSED_SHOT
3     78.17    -10.17         GOAL
4    -87.24     34.40         GOAL
5    -96.10     30.41         GOAL

>>> df.loc[df.coords_x < 0, ['coords_x', 'coords_y']] *= -1
>>> df
   coords_x  coords_y   event_type
0      4.07    -21.75         GOAL
1      2.46     20.99         SHOT
2     99.45    -15.09  MISSED_SHOT
3     78.17    -10.17         GOAL
4     87.24    -34.40         GOAL
5     96.10    -30.41         GOAL
Related