Conditionally filling blank values in Pandas dataframes

后端 未结 3 1262
误落风尘
误落风尘 2021-01-22 20:41

I have a datafarme which looks like as follows (there are more columns having been dropped off):

    memberID    shipping_country    
    264991      
    264991         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 21:12

    You can use GroupBy + ffill / bfill:

    def filler(x):
        return x.ffill().bfill()
    
    res = df.groupby('memberID')['shipping_country'].apply(filler)
    

    A custom function is necessary as there's no combined Pandas method to ffill and bfill sequentially.

    This also caters for the situation where all values are NaN for a specific memberID; in this case they will remain NaN.

提交回复
热议问题