gpt4 book ai didi

python - 有没有办法在 Python-Pandas 中多重过滤 Dataframe?

转载 作者:行者123 更新时间:2023-12-05 00:09:57 26 4
gpt4 key购买 nike

寻找某种方法来通过几个条件过滤我的数据框(例如数据框:

id  Arrest  Shift_num  Description
0 True 20 Weapon
1 False 25 unarmed
2 True 30 Weapon

我想通过以下方式获得 DF:
说明 == 武器和 shift_num >= 25arrest == True (例如)

经过几次尝试,这是我的方式,但我认为它可以比这更好:
arrest=(df.Arrest == True)
shift=(df.Shift_num >= 25)
weap= (df['Description'] == 'weapon')

print(df[arrest & shift & weap])

提前致谢 :)

最佳答案

您可以使用 df.query (奖励:它使用了 numexpr,这是非常优化的!):

import pandas as pd

df = pd.DataFrame({"Arrest": [True, False, True],
"Shift_num": [20, 25, 30],
"Description": ["Weapon", "unarmed", "Weapon"]})

df.query("Arrest & Shift_num >= 25 & Description == 'Weapon'")

输出:
   Arrest  Shift_num Description
2 True 30 Weapon

一些注意事项:
  • 不要忘记“引用”字符串
  • 可以使用的变量名称来自 DataFrame 范围(无需使用前缀 df )
  • 使用 ~Arrest当你不想被捕
  • 您可以使用 @引用作用域中的变量(即不在 df 中)

  • 我鼓励你阅读 numexpr .

    关于python - 有没有办法在 Python-Pandas 中多重过滤 Dataframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182578/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com