【问题标题】:Python Dataframe: How to map a column value with adjacent columns value?Python Dataframe:如何将列值与相邻列值映射?
【发布时间】:2020-09-09 14:27:07
【问题描述】:

使用带有 python 的 pandas 将列值与相邻列值映射 有一个带有值的df

name          exm_date                         att_date    
tom       2019-03-05 11:48:03.166             2020-03-05 11:48:03.166 
mark      2018-03-05 11:48:03.166             2020-03-05 11:48:03.166     
matt      2020-08-05 11:48:03.166              NAT
rob       2020-06-05 11:48:03.166              NAT
chuck     2020-02-05 11:48:03.166              NAT
tom       2020-03-05 11:48:03.166              NAT
matt      2020-02-05 11:48:03.166             2020-03-05 11:48:03.166     
chuck     2020-06-05 11:48:03.166             2020-03-05 11:48:03.166                       

对于 att_date 中具有 NAT 的值,应从 exm_date 中选择日期 预期输出:

name          exm_date                         att_date    
tom       2019-03-05 11:48:03.166             2020-03-05 11:48:03.166 
mark      2018-03-05 11:48:03.166             2020-03-05 11:48:03.166     
matt      2020-08-05 11:48:03.166             2020-08-05 11:48:03.166 
rob       2020-06-05 11:48:03.166             2020-06-05 11:48:03.166  
chuck     2020-02-05 11:48:03.166             2020-02-05 11:48:03.166
tom       2020-03-05 11:48:03.166             2020-03-05 11:48:03.166
matt      2020-02-05 11:48:03.166             2020-03-05 11:48:03.166     
chuck     2020-06-05 11:48:03.166             2020-03-05 11:48:03.166     

【问题讨论】:

  • 如果 NAT 不是文本,并且实际上为空,df.ffill(axis=1) 将在同一行使用 exm_date 值填充 att_date。

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

您可以使用 apply 方法来替换缺失值:

df['att_date'] = df.apply(
    lambda row: row['exm_date'] if row['att_date'] == 'NAT' else row['att_date'],
    axis=1)

【讨论】:

    【解决方案2】:

    您可以将.loc 与一个布尔值一起使用,如果 att_date 为空,则计算结果为True

    df.loc[df['att_date'].isna(),'att_date'] = df['exm_date']
    print(df)
         name          exm_date                att_date
    0    tom 2019-03-05 11:48:03.166 2020-03-05 11:48:03.166
    1   mark 2018-03-05 11:48:03.166 2020-03-05 11:48:03.166
    2   matt 2020-08-05 11:48:03.166 2020-08-05 11:48:03.166
    3    rob 2020-06-05 11:48:03.166 2020-06-05 11:48:03.166
    4  chuck 2020-02-05 11:48:03.166 2020-02-05 11:48:03.166
    5    tom 2020-03-05 11:48:03.166 2020-03-05 11:48:03.166
    6   matt 2020-02-05 11:48:03.166 2020-03-05 11:48:03.166
    7  chuck 2020-06-05 11:48:03.166 2020-03-05 11:48:03.166
    

    【讨论】:

      【解决方案3】:

      您可以使用fillna 或combine_first

      df['att_date'] = df['att_date'].fillna(df['exm_date'])
      #or
      df['att_date'] = df['att_date'].combine_first(df['exm_date'])
      

      【讨论】:

        猜你喜欢
        • 2018-05-16
        • 1970-01-01
        • 2016-09-02
        • 2021-03-09
        • 1970-01-01
        • 2021-06-12
        • 2020-10-20
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多