gpt4 book ai didi

python - 如何将 str.startswith 用于多列?

转载 作者:行者123 更新时间:2023-12-02 03:28:44 25 4
gpt4 key购买 nike

我有一个如下所示的数据框: my data

我用它来过滤 ID 以 b、c、e、f、5 开头的用户,并且能够成功执行此操作。

df[df.userA.str.startswith(('b','c','e','f','5'))]

我现在想对列 userA 和 userB 执行相同的操作,但尝试运行失败:

df[[df.userA.str.startswith(('b','c','e','f','5'))] and [df.userB.str.startswith(('b','c','e','f','5'))]]

有什么想法吗?

最佳答案

您不能使用 and,因为在 Python 中这将返回 第一个 具有真实性 False 的操作数(或者在没有这样的情况下 链中的操作数,最后一个元素)。

不过,您可以使用 &| 运算符分别作为逻辑 andor 来应用多个条件。

所以对于你的情况,你可能想使用:

df[
df.userA.str.startswith(('b','c','e','f','5')) <b>&</b>
df.userB.str.startswith(('b','c','e','f','5'))
]

(这给出了数据帧 df 的“行”,两者 userAuserB('b','c','e','f','5') 中的一个字符;或

df[
df.userA.str.startswith(('b','c','e','f','5')) <b>|</b>
df.userB.str.startswith(('b','c','e','f','5'))
]

(这给出了数据帧 df 的“行”,至少 userAuserB 开始在 ('b','c','e','f','5'))

中有一个字符

有关更多信息,请参阅 Boolean indexing in the pandas documentation 上的文档.

关于python - 如何将 str.startswith 用于多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52458085/

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