gpt4 book ai didi

python - 如何根据条件更改 Pandas 系列中的值

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

我有一个只有二进制值的 pandas 系列

    0
0 1
1 0
2 0
3 0
4 1
5 0
6 1
7 0
8 0
9 1
10 0
11 1
12 0
13 1
14 0

我想隐藏系列中的值,它是零,它周围有一个,即基本上将 1、0、1 更改为 1、1、1。

我需要的输出是:

0     1
1 0
2 0
3 0
4 1
5 1
6 1
7 0
8 0
9 1
10 1
11 1
12 1
13 1
14 0

我在这里尝试的是创建一个 3 的滚动窗口并检查值是否是我需要的。有没有更好的方法来解决这个问题?

>>> window = df.rolling(3, center=True)
>>> (df[0] | window.apply(lambda x: 1 if (x == [1,0,1]).all() else 0)[0].fillna(0)).astype(int)

注意:我也尝试过 shift 功能。

最佳答案

使用shift对于 bool 掩码并通过 numpy.where 设置 1 :

m1 = df[0].shift() == 1
m2 = df[0].shift(-1) == 1
m3 = df[0] == 0

df[0] = np.where(m1 & m2 & m3, 1, df[0])

print (df)
0
0 1
1 0
2 0
3 0
4 1
5 1
6 1
7 0
8 0
9 1
10 1
11 1
12 1
13 1
14 0

关于python - 如何根据条件更改 Pandas 系列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53411241/

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