gpt4 book ai didi

python - 使用不在 pandas 中的向量化逻辑来过滤帧

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

我有一个 pandas 数据框,我想修剪。我想取出部分为 2 并且标识符不以数字开头的行。首先我想数一下它们。如果我运行这个

len(analytic_events[analytic_events['section']==2].index)

我得到结果1247669

当我缩小范围并运行它时

len(analytic_events[(analytic_events['section']==2) & ~(analytic_events['identifier'][0].isdigit())].index)

我得到完全相同的答案:1247669

例如,我知道其中十行将此作为标识符

.help.your_tools.subtopic2

不以数字开头,并且 15,000 行以此作为标识符

240.1007

其中确实以数字开头。

为什么我的过滤器会传递所有行,而不是仅传递标识符不以数字开头的行?

最佳答案

使用str处理文本函数,使用str[0]作为字符串的第一个值,最后一个sum作为计数True 的值:

mask= ((analytic_events['section']==2) & 
~(analytic_events['identifier'].str[0].str.isdigit()))

print (mask.sum())

如果性能很重要并且没有缺失值,请使用列表理解:

arr = ~np.array([x[0].isdigit() for x in analytic_events['identifier']])
mask = ((analytic_events['section']==2) & arr)

编辑:

Why is my filter passing all the rows rather than just those whose identifier does not start with a digit?

如果测试解决方案的输出:

analytic_events = pd.DataFrame(
{'section':[2,2,2,3,2],
'identifier':['4hj','8hj','gh','th','h6h']})

print (analytic_events)
section identifier
0 2 4hj
1 2 8hj
2 2 gh
3 3 th
4 2 h6h

获取列的第一个值:

print ((analytic_events['identifier'][0]))
4hj

检查标量是否为数字:

print ((analytic_events['identifier'][0].isdigit()))
False

print (~(analytic_events['identifier'][0].isdigit()))
-1

对于带有第一个掩码的链,它被转换为True:

print ((analytic_events['section']==2) & ~(analytic_events['identifier'][0].isdigit()))
0 True
1 True
2 True
3 False
4 True
Name: section, dtype: bool

所以它的工作方式与第二个掩码不存在相同:

print (analytic_events['section']==2)
0 True
1 True
2 True
3 False
4 True
Name: section, dtype: bool

关于python - 使用不在 pandas 中的向量化逻辑来过滤帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439536/

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