在 pandas/numpy python 中使用同一列的 2 个数组进行向量化计算

问题描述 投票:0回答:1

我有一个向量计算,它从数组中获取一个值以及该数组下面的值。它检查上面的值是否为 1,下面的值是否为 0。如果是这种情况,使用 np.where 我将为 true 分配 1,为 false 分配 0。我似乎得到的错误是:“无法将输入数组从形状 (6,) 广播到形状 (5,)”。

import pandas as pd
import numpy as np
data = {
    'A': [0, 0, 1, 0, 0, 0],
    'B': [0,0,0,0,0,0]
}
df = pd.DataFrame(data)
x=1
df.iloc[0:5,1]=np.where((df.iloc[0:5,0]==1) & (df.iloc[1:6,0]==0),x,0)

每个

df.iloc
大小相同,最后一行只是一个虚拟行,以允许
df.iloc[1:6,0]
工作。

另外,当运行布尔值时,我得到:

(df.iloc[0:5,0]==1) & (df.iloc[1:6,0]==0)
Out[43]: 
0    False
1    False
2    False
3    False
4    False
5    False

但值 2 应该为 true。我也尝试过将 x 设为数组,但似乎不起作用,任何帮助将不胜感激!

python pandas numpy vectorization
1个回答
0
投票

具体逻辑不清楚,但是需要使用

shift
:

# the current value is 1 and the below value is 0
m = df['A'].eq(1) & df['A'].shift(-1).eq(0)
df['out'] = np.where(m, 1, 0)

# the above value is 1 and the below value is 0
m2 = df['A'].shift().eq(1) & df['A'].shift(-1).eq(0)
df['out2'] = np.where(m2, 1, 0)

如果您想将

True
映射到
1
并将
False
映射到
0
,则不需要
np.where
,只需使用
m.astype(int)
即可。

输出:

   A  B  out  out2
0  0  0    0     0
1  0  0    0     0
2  1  0    1     0
3  0  0    0     1
4  0  0    0     0
5  0  0    0     0
© www.soinside.com 2019 - 2024. All rights reserved.