【问题标题】:How to assign a "null" value from another column?如何从另一列分配一个“空”值?
【发布时间】:2022-12-05 00:05:19
【问题描述】:

我想创建一个名为“season_new”的新列,我想在其中维护非空季节并从节目名称中提取空值的季节。我的数据框是这样的:

programme season
grey's anatomy s1 null
friends season 1 1
grey's anatomy s2 null
big bang theory s2 2
big bang theory 1
peaky blinders 1

我会尝试使用正则表达式。

dt['season_new'] = dt['programme'].str.extract(r'(season\s?\d+|s\s?\d+)')

但它给了我这个结果:

programme season season_new
grey's anatomy s1 null 1
friends season 1 1 1
grey's anatomy s2 null 2
big bang theory s2 2 2
big bang theory 1 null
peaky blinders 1 null

我期望的结果是:

programme season season_new
grey's anatomy s1 null 1
friends season 1 1 1
grey's anatomy s2 null 2
big bang theory s2 2 2
big bang theory 1 1
peaky blinders 1 1

【问题讨论】:

    标签: python pandas regex


    【解决方案1】:

    您可以使用pandas.Series.fillna,因为这个接受系列作为value

    值:标量,字典,系列, 或数据框

    尝试这个 :

    dt['season_new'] = (
                        dt['programme']
                            .str.extract(r'[seasons?|s](d+)', expand=False)
                            .fillna(dt['season'])
                            .astype(int)
                        )
    

    如果要删除旧季节,请使用 pandas.Series.pop

    dt['season_new'] = (
                        dt['programme']
                            .str.extract(r'[seasons?|s](d+)', expand=False)
                            .fillna(dt.pop('season'))
                            .astype(int)
                        )
    

    # 输出 :

    print(dt)
    
                programme  season_new
    0   grey's anatomy s1           1
    1    friends season 1           1
    2   grey's anatomy s2           2
    3  big bang theory s2           2
    4     big bang theory           1
    5      peaky blinders           1
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多