np,其中有两个条件且首先满足

2024-10-03 09:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据两个条件创建一个目标变量。我有X值是二进制的,X2值也是二进制的。我的条件是,当nVer X从1变为0时,只有在X2中从0变为1时,y中才有1。如果这之后是X中从0到1的变化,那么我们一开始就不做这种变化。我附上了一张excel中的图片

为了解释X的变化,我也做了以下几点

df['X-prev']=df['X'].shift(1)
df['Change-X;]=np.where(df['X-prev']+df['X']==1,1,0)
# this is the data frame 
X=[1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0]
X2=[0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1]
df=pd.DataFrame()
df['X']=X
df['X2']=X2

然而,这还不够,因为我需要知道X变化之后的第一个变化。我附上了一张例子的照片

非常感谢所有的贡献Example


Tags: 目标dfshiftisnp二进制图片this
1条回答
网友
1楼 · 发布于 2024-10-03 09:15:51

保留与转换匹配的行(X=1, X+1=0)(X2=1, X2-1=0),然后将所有选定行合并到一个列表中,其中0表示“开始一个周期”,1表示“结束一个周期”

但在此列表中,您可以有连续的开始或结束,因此您需要再次筛选以仅获得(0,1)个周期。之后,用原始数据帧索引重新索引这个新系列,并用1填充

x1 = df['X'].sub(df['X'].shift(-1)).eq(1)
x2 = df['X2'].sub(df['X2'].shift(1)).eq(1)

sr1 = pd.Series(0, df.index[x1])
sr2 = pd.Series(1, df.index[x2])
sr = pd.concat([sr2, sr1]).sort_index()

df['Y'] = sr[sr.lt(sr.shift(-1)) | sr.gt(sr.shift(1))] \
            .reindex(df.index).bfill().fillna(0).astype(int)
>>> df

    X  X2  Y
0   1   0  0  # start here: (X=1, X+1=0) but never ended before another start
1   1   0  0
2   0   0  0
3   0   0  0
4   1   0  0  # start here: (X=1, X+1=0)
5   0   0  1  # <- fill with 1
6   0   0  1  # <- fill with 1
7   0   0  1  # <- fill with 1
8   0   0  1  # <- fill with 1
9   0   1  1  # end here: (X2=1, X2-1=0) so fill back rows with 1
10  0   1  0
11  0   1  0
12  0   1  0
13  0   1  0
14  0   0  0
15  0   0  0
16  0   1  0  # end here: (X2=1, X2-1=0) but never started before
17  0   0  0
18  0   0  0
19  0   0  0
20  1   0  0
21  1   0  0  # start here: (X=1, X+1=0)
22  0   0  1  # <- fill with 1
23  0   0  1  # <- fill with 1
24  0   0  1  # <- fill with 1
25  0   0  1  # <- fill with 1
26  0   0  1  # <- fill with 1
27  0   1  1  # end here: (X2=1, X2-1=0) so fill back rows with 1
28  0   1  0
29  0   1  0

相关问题 更多 >