首页 文章

(pandas)根据groupby和column条件填充NaN

提问于
浏览
3

在groupby元素上使用'bfill'或'ffill'是微不足道的,但是如果你需要根据第三列中的条件在第二列中用特定值填充na呢?

例如:

>>> df=pd.DataFrame({'date':['01/10/2017', '02/09/2017', '02/10/2016','01/10/2017', '01/11/2017', '02/10/2016'], 'a':[1,1,1,2,2,2], 'b':[4,np.nan,6, 5, np.nan, 7]})
>>> df
   a    b        date
0  1  4.0  01/10/2017
1  1  NaN  02/09/2017
2  1  6.0  02/10/2016
3  2  5.0  01/10/2017
4  2  NaN  01/11/2017
5  2  7.0  02/10/2016

我需要按列'a'进行分组,并使用列'b'值填充NaN,其中该行的日期最接近NaN行中的日期 .

所以输出应该如下:

a    b        date
0  1  4.0  01/10/2017
1  1  6.0  02/09/2017
2  1  6.0  02/10/2016
3  2  5.0  01/10/2017
4  2  5.0  01/11/2017
5  2  7.0  02/10/2016

假设有一个nearest_date()函数,它接受NaN日期和该组中其他日期的列表,并返回最接近的日期 .

我正在尝试找到一个不需要遍历行的干净解决方案,理想情况下能够将apply()与lambdas一起使用 . 有任何想法吗?

2 回答

  • 0

    这应该工作:

    df['closest_date_by_a'] = df.groupby('a')['date'].apply(closest_date)
    df['b'] = df.groupby(['a', 'closest_date_by_a'])['b'].ffill().bfill()
    

    给定一个函数( closest_date() ),您需要按组应用该函数,以便计算每个组中行的最接近日期 . 然后,您可以按主分组列( a )和最近的日期列( closest_date_by_a )进行分组,然后执行填充 .

  • 0

    确保 date 列实际上是日期 .

    df = pd.DataFrame(
        {'date': ['01/10/2017', '02/09/2017', '02/10/2016','01/10/2017', '01/11/2017', '02/10/2016'],
         'a':[1,1,1,2,2,2], 'b':[4,np.nan,6, 5, np.nan, 7]})
    df.date = pd.to_datetime(df.date)
    
    print(df)
    
       a    b       date
    0  1  4.0 2017-01-10
    1  1  NaN 2017-02-09
    2  1  6.0 2016-02-10
    3  2  5.0 2017-01-10
    4  2  NaN 2017-01-11
    5  2  7.0 2016-02-10
    

    拥有 dropna() 之后使用 reindexmethod='nearest'

    def fill_with_nearest(df):
        s = df.set_index('date').b
        s = s.dropna().reindex(s.index, method='nearest')
        s.index = df.index
        return s
    
    df.loc[df.b.isnull(), 'b'] = df.groupby('a').apply(fill_with_nearest).reset_index(0, drop=True)
    
    print(df)
    
       a    b       date
    0  1  4.0 2017-01-10
    1  1  4.0 2017-02-09
    2  1  6.0 2016-02-10
    3  2  5.0 2017-01-10
    4  2  5.0 2017-01-11
    5  2  7.0 2016-02-10
    

相关问题