簡體   English   中英

pandas ffill基於另一欄中的條件

[英]pandas ffill based on condition in another column

我有一個pandas DataFrame,如下所示。

df = pd.DataFrame({
    'date': ['2011-01-01', '2011-01-01', '2011-02-01', '2011-02-01', '2011-03-01', '2011-03-01', '2011-04-01', '2011-04-01'],
    'category': [1, 2, 1, 2, 1, 2, 1, 2],
    'rate': [0.5, 0.75, np.nan, np.nan, 1, 1.25, np.nan, np.nan]
})

我想使用ffill來轉發填充rate的值,除了我希望每個值也對應於相應的category 我怎么能讓df看起來像這樣?:

df
    category    date    rate
    1     2011-01-01    0.50
    2     2011-01-01    0.75
    1     2011-02-01    0.50
    2     2011-02-01    0.75
    1     2011-03-01    1.00
    2     2011-03-01    1.25
    1     2011-04-01    1.00
    2     2011-04-01    1.25

使用groupby

df.groupby('category').ffill()

輸出:

   category        date  rate
0         1  2011-01-01  0.50
1         2  2011-01-01  0.75
2         1  2011-02-01  0.50
3         2  2011-02-01  0.75
4         1  2011-03-01  1.00
5         2  2011-03-01  1.25
6         1  2011-04-01  1.00
7         2  2011-04-01  1.25

如果你有其他你想要填充NaN的列,那么你可以使用它來在rate列中填充NaN:

df['rate'] = df.groupby('category')['rate'].ffill()

暫無
暫無

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

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