簡體   English   中英

Pandas 前向填充 ffill() 直到另一列的條件為假

[英]Pandas forward fill ffill() until the condition of another column is false

我有一個包含三列的 dataframe。 最后一列是“值”,一旦“打開”指示器為 1,我希望它返回“t”,直到“關閉”指示器打開。

d1={'on?':[0,1,0,0,0,1,0,0,0],'off?':[0,0,0,1,0,0,0,0,0],'value':[0,1,1,0,0,1,1,1,1]} df=pd.DataFrame(d1)

下面是我想要的 output。 我嘗試使用df['value']=np.where(df['on?']==1,1,0)但顯然它適用於整個列並且不會停止填充,因為它與'off? '。

有人可以指導我通過什么是最好的 function 進行前向填充 function 直到滿足/不滿足特定條件?

[期望的輸出1

In [27]: df
Out[27]:
   on?  off?
0    0     0
1    1     0
2    0     0
3    0     1
4    0     0
5    1     0
6    0     0
7    0     0
8    0     0

In [28]: df['value'] = (df['on?'] - df['off?']).cumsum()

In [29]: df
Out[29]:
   on?  off?  value
0    0     0      0
1    1     0      1
2    0     0      1
3    0     1      0
4    0     0      0
5    1     0      1
6    0     0      1
7    0     0      1
8    0     0      1

如果您認為它可能更容易理解

  1. a = df['on?'].cumsum()它為您提供了 ons 的累積總和
  2. b = df['off?'].cumsum()它給你一個累積的offs總和
  3. 然后你需要的是a - b ie df['on?'].cumsum() - df['off?'].cumsum()可以簡化為(df['on?'] - df['off?']).cumsum()

編輯:根據評論 -

上述解決方案的一個問題是 IF 值 1 首先出現在 Off? 列,則該值將從 -1 開始,並且只會在 0 和 -1 之間變化。 如何解決這個問題/設置一個最小值/一個不計分的條件? 直到上? 指示燈亮?


In [161]: df['on_count'] = df['on?'].cumsum()

In [162]: df
Out[162]:
   on?  off?  on_count
0    0     1         0
1    1     0         1
2    0     0         1
3    0     1         1
4    0     1         1
5    1     0         2
6    0     0         2
7    0     0         2
8    0     0         2

您可以按“on_count”分組 - 這是 on 列的 cumsum; 然后應用相同的邏輯

In [170]: grouped_cumsum = df.groupby('on_count')[['on?', 'off?']].cumsum()

In [171]: grouped_cumsum
Out[171]:
   on?  off?
0    0     1
1    1     0
2    1     0
3    1     1
4    1     2
5    1     0
6    1     0
7    1     0
8    1     0

In [174]: df['value'] = (grouped_cumsum['on?'] - grouped_cumsum['off?'])

In [175]: df.loc[df['value'] < 0, 'value'] = 0 # or however else you wan't to deal with

In [177]: df.drop(columns='on_count')
Out[177]:
   on?  off?  value
0    0     1      0
1    1     0      1
2    0     0      1
3    0     1      0
4    0     1      0
5    1     0      1
6    0     0      1
7    0     0      1
8    0     0      1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM