python - 根据条件修改数据框中的 2 列

标签 python pandas dataframe

我在 Stack Overflow 上看到了一堆关于如何根据条件修改数据框中的单个列的示例,但我不知道如何根据单个条件修改多个列。

如果我有一个基于以下代码生成的数据框 -

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

我想要完成的是 DataFrame 每一行的以下内容(伪代码)-

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

有没有办法通过我缺少的 df.apply() 函数来做到这一点?

预先感谢您的帮助!

最佳答案

IIUC,您可以使用 loc 执行此操作,避免需要 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

关于python - 根据条件修改数据框中的 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125284/

相关文章:

python - 以其他列组的最大值为条件计算新列

python - 为什么 mypy 在无法注释时提示列表理解?

python - 如何在 3D-Pandas Dataframe 中查找包含特定子列/嵌套列的列

python - 来自序列化程序的自定义字段的 Django Rest Order?

python - 在 Twilio 回复中发送多条 SMS 消息

python - 在 Python 中创建具有多个操作的函数

python - 切片具有相同索引号 pandas 的行

r - 将向量添加到 R 列表中子列出的每个数据帧

python - 使用 pd.read_csv() 读取多个文件并将每个文件保存为不同的变量

algorithm - 为什么我不能遍历数据框中的新列?