![](/img/trans.png)
[英]How can I forward fill a dataframe column where the limit of rows filled is based on the value of a cell in another column?
[英]Backwards fill dataframe column where limit of rows filled is based on value of cell, perhaps with bfill() and limit=x
我有一個看起來像這樣的 dataframe:
import pandas as pd, numpy as np
df = pd.DataFrame({'Fill' : [0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 1]})
df['flag'] = (df['Fill'] > 0)
df = df.replace(0,np.nan)
df
Fill flag
0 NaN False
1 NaN False
2 NaN False
3 3.0 True
4 NaN False
5 NaN False
6 NaN False
7 2.0 True
8 NaN False
9 NaN False
10 1.0 True
我的目標是使用bfill()
反向填充,並根據Fill
列中單元格的值傳遞動態limit
。 我還創建了一個flag
列,對於任何 > 0 的單元格都是True
。我這樣做是為了防止Fill
列中的值在填充時可能會變成浮點數,所以我不想應用邏輯 o那些以 NaN 開頭的單元格。 這是我嘗試過的:
df['Fill'] = np.where((df['Fill'].notnull()) & (df.flag==True),
df['Fill'].apply(lambda x: x.bfill(limit=int(x-1))),
df['Fill'])
我收到一個錯誤: AttributeError: 'float' object has no attribute 'bfill'
,但我認為因為我正在使用np.where
過濾相關行,所以我可以繞過 nan 值和int(x-1)
,我可以避免浮動問題。 我還嘗試了與 .apply 內部的.apply
類似的東西。 任何幫助深表感謝。 請參閱下面的預期 output:
預期 output:
Fill flag
0 NaN False
1 3.0 False
2 3.0 False
3 3.0 True
4 NaN False
5 NaN False
6 2.0 False
7 2.0 True
8 NaN False
9 NaN False
10 1.0 True
您可以為每個缺失值和最后一個非缺失值創建組,並用自定義 function 中的最后一個值替換, if-else
是避免錯誤ValueError: Limit must be greater than 0
:
m = df['Fill'].notnull() & df.flag
g = m.iloc[::-1].cumsum().iloc[::-1]
f = lambda x: x.bfill(limit=int(x.iat[-1]-1)) if x.iat[-1] > 1 else x
df['Fill'] = df.groupby(g)['Fill'].apply(f)
print (df)
Fill flag
0 NaN False
1 3.0 False
2 3.0 False
3 3.0 True
4 NaN False
5 NaN False
6 2.0 False
7 2.0 True
8 NaN False
9 NaN False
10 1.0 True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.