gpt4 book ai didi

python - Pandas Series.ne 运算符针对同一系列的两个切片返回意外结果

转载 作者:行者123 更新时间:2023-11-30 22:19:59 26 4
gpt4 key购买 nike

所以我有如下所示的这一系列整数

from pandas import Series
s = Series([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

我想看看数字在整个系列中变化了多少次,这样我就可以执行以下操作并获得预期的结果。

[i != s[:-1][idx] for idx, i in enumerate(s[1:])]
Out[5]:
[True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
False,
False,
False,
False,
False,
False,
False,
False,
False]

从那里我可以简单地计算出 True 的当前数量。但这显然不是在 pandas 系列上操作的最佳方式,并且我在性能很重要的情况下添加了此方法,因此我执行了以下操作,期望得到相同的结果,但我感到非常惊讶和困惑。

s[1:].ne(s[:-1])
Out[4]:
0 True
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 False
11 False
12 False
13 False
14 False
15 False
16 False
17 False
18 False
19 False
20 False
21 False
22 False
23 False
24 False
25 False
26 False
27 False
28 False
29 False
30 False
31 False
32 False
33 False
34 False
35 False
36 False
37 False
38 False
39 True
dtype: bool

使用 Series.ne 方法的输出不仅对我来说没有任何逻辑意义,而且输出也比任何一个输入都长,这尤其令人困惑。

我认为这可能与此https://github.com/pandas-dev/pandas/issues/1134有关

无论如何,我很好奇我做错了什么以及实现这一目标的最佳方法是什么。

tl;博士:

其中 s 是 pandas.Series 的 int

[i != s[:-1][idx] for idx, i in enumerate(s[1:])] != s[:-1].ne(s[1:]) .tolist()

编辑谢谢大家,阅读下面的一些答案,可能的解决方案是 sum(s.diff().astype(bool)) - 1 但是我仍然很好奇为什么上述解决方案不起作用

最佳答案

您可以利用diff

>>> from pandas import Series
>>> s = Series([1, 2, 1, 3, 3, 1, 1])
>>> s.diff()
0 NaN
1 1.0
2 -1.0
3 2.0
4 0.0
5 -2.0
6 0.0
dtype: float64
>>> s.diff().ne(0) # Same of s.diff() != 0
0 True
1 True
2 True
3 True
4 False
5 True
6 False
dtype: bool
>>> # To know how many times the values had changed simply count the
... # number of True, except the first which is fault of the NaN
... # generated by `diff()` function.
...
>>> sum(s.diff().ne(0)) - 1
4

关于python - Pandas Series.ne 运算符针对同一系列的两个切片返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935958/

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