【问题标题】:Forward fill or back fill NaN values in Pandas columns based on grouping of other columns根据其他列的分组,前向填充或后向填充 Pandas 列中的 NaN 值
【发布时间】:2019-11-21 17:51:00
【问题描述】:

我有一个如下的数据框:

import pandas as pd

df = pd.DataFrame({'Country':['USA','USA','MEX','IND','UK','UK','UK'],
                   'Region':['Americas','NaN','NaN','Asia','Europe','NaN','NaN'],
                   'Flower':['Rose','Rose','Lily','Orchid','Dandelion','Dandelion','Dandelion'],
                   'Animal':['Bison','NaN','Golden Eagle','Tiger','Lion','Lion','NaN'],
                   'Game':['Baseball','Baseball','soccer','hockey','cricket','cricket','cricket']})

我想按Country 和Flower 分组,并向前填充或向后填充有缺失值的列Region 和Animal。但是Game 列应该保持不变

我试过了,但是没用:

df['Region'] = df.groupby(['Country','Flower'])['Region'].transform(lambda x: x.ffill())

还有:

df.groupby(['Country','Flower'])['Animal', 'Region'].isna().bfill()

我想知道该怎么做。

虽然这可行,但它会删除 Games 列:

df=df.replace({'NaN':np.nan}) df.groupby(['Country','Flower'])['Animal', 'Region'].bfill().ffill()

如果我进行转换,则长度不匹配。另请注意,这是示例数据帧,我在原始帧中添加了“NaN”作为字符串,它是 np.nan。

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    首先你需要知道'NaN'不是NaN

    df=df.replace({'NaN':np.nan})
    df.groupby(['Country','Flower'])['Region'].ffill()
    Out[109]: 
    0    Americas
    1    Americas
    2         NaN# since here only have single row , that why stay NaN
    3        Asia
    4      Europe
    5      Europe
    6      Europe
    Name: Region, dtype: object
    

    第二个如果你需要在pandas中链接两个iid函数你需要apply

    df.update(df.groupby(['Country','Flower'])['Animal', 'Region'].apply(lambda x : x.bfill().ffill()))                               
    df
    Out[119]: 
             Animal Country     Flower      Game    Region
    0         Bison     USA       Rose  Baseball  Americas
    1         Bison     USA       Rose  Baseball  Americas
    2  Golden Eagle     MEX       Lily    soccer       NaN
    3         Tiger     IND     Orchid    hockey      Asia
    4          Lion      UK  Dandelion   cricket    Europe
    5          Lion      UK  Dandelion   cricket    Europe
    6          Lion      UK  Dandelion   cricket    Europe
    

    【讨论】:

      【解决方案2】:

      如果您将数据框代码更改为实际包含 np.nans,那么您提供的代码实际上可以工作。尽管 nans 显示为普通文本“Nan”,但您无法创建手动写入该文本的数据框,因为这将被解释为字符串,而不是实际的缺失值。

      import pandas as pd
      import numpy as np
      
      df = pd.DataFrame({'Country':['USA','USA','MEX','IND','UK','UK','UK'],
                         'Region':['Americas',np.nan,np.nan,'Asia','Europe',np.nan,np.nan],
                         'Flower':['Rose','Rose','Lily','Orchid','Dandelion','Dandelion','Dandelion'],
                         'Animal':['Bison',np.nan,'Golden Eagle','Tiger','Lion','Lion','NaN'],
                         'Game':['Baseball','Baseball','soccer','hockey','cricket','cricket','cricket']})
      

      那么,这个:

      df['Region'] = df.groupby(['Country','Flower'])['Region'].transform(lambda x: x.ffill())
      

      实际上产生了这个:

               Animal Country     Flower      Game    Region
      0         Bison     USA       Rose  Baseball  Americas
      1           NaN     USA       Rose  Baseball  Americas
      2  Golden Eagle     MEX       Lily    soccer       NaN
      3         Tiger     IND     Orchid    hockey      Asia
      4          Lion      UK  Dandelion   cricket    Europe
      5          Lion      UK  Dandelion   cricket    Europe
      6           NaN      UK  Dandelion   cricket    Europe
      

      【讨论】:

      • 没错,只是复制了他的建议,只是为了强调它没有任何问题。
      猜你喜欢
      • 2019-06-06
      • 2020-11-14
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      相关资源
      最近更新 更多