gpt4 book ai didi

python - 过滤 Pandas 行,其中列中的第一个字母是/不是某个值

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:48 25 4
gpt4 key购买 nike

如何过滤掉我不希望第一个字母为“Z”或任何其他字符的一系列数据(在 pandas dataFrame 中)。

我有以下 pandas 数据框 df(其中有 > 25,000 行)。

TIME_STAMP  Activity    Action  Quantity    EPIC    Price   Sub-activity    Venue
0 2017-08-30 08:00:05.000 Allocation BUY 50 RRS 77.6 CPTY 066
1 2017-08-30 08:00:05.000 Allocation BUY 50 RRS 77.6 CPTY 066
3 2017-08-30 08:00:09.000 Allocation BUY 91 BATS 47.875 CPTY PXINLN
4 2017-08-30 08:00:10.000 Allocation BUY 43 PNN 8.07 CPTY WCAPD
5 2017-08-30 08:00:10.000 Allocation BUY 270 SGE 6.93 CPTY PROBDMAD

我正在尝试删除 Venue 第一个字母为“Z”的所有行。

例如,我通常的过滤器代码类似于(过滤掉 Venue = '066' 的所有行

df = df[df.Venue != '066']

我可以看到这个过滤器行过滤掉了我需要的数组,但我不确定如何在过滤器上下文中指定它。

[k for k in df.Venue if 'Z' not in k]

最佳答案

使用 str[0] 选择第一个值或使用 startswith , contains使用正则表达式 ^ 作为字符串的开头。对于反转 bool 掩码,使用 ~:

df1 = df[df.Venue.str[0] != 'Z']

df1 = df[~df.Venue.str.startswith('Z')]

df1 = df[~df.Venue.str.contains('^Z')]

如果没有 NaN 的值更快,则使用列表理解:

df1 = df[[x[0] != 'Z' for x in df.Venue]]

df1 = df[[not x.startswith('Z') for x in df.Venue]]

关于python - 过滤 Pandas 行,其中列中的第一个字母是/不是某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52587870/

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