簡體   English   中英

向后填充 dataframe 列,其中填充的行數限制基於單元格的值,可能使用 bfill() 和 limit=x

[英]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.

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