代码之家  ›  专栏  ›  技术社区  ›  PineNuts0

Python数据框:如果列中的值等于字符串,第二列中的AND值为Null,则用另一个字符串替换Null单元格

  •  0
  • PineNuts0  · 技术社区  · 1 年前

    下面是以下python数据帧示例:

    类型 价值
    a. 芝麻
    b
    a.
    c 茶叶
    a. 小面包

    创建该表的代码如下:

    import pandas as pd
    df = pd.DataFrame({'Type':["A","B","A", "C", "A"],'Value':["sesame", None, None, "tea", "bun"]})
    

    我想做以下事情:

    • 如果Type列等于“A”且Value列为null,则将null替换为“custard”
    • 如果Type列等于“B”且Value列为null,则将null替换为“花生”
    • 否则,保留“值”列为原样

    我想要的输出表如下:

    类型 价值
    a. 芝麻
    b 花生
    a. 蛋奶沙司
    c 茶叶
    a. 小面包

    我似乎连第一个要点都想不通。我尝试了以下代码:

    df.loc[df['Type'] == 'A', ['Value']].fillna(value='custard', axis=1)
    

    但它产生了错误的输出: enter image description here

    1 回复  |  直到 1 年前
        1
  •  1
  •   Hildermes José Medeiros Filho    1 年前

    使用empt值比较在相等条件下返回false的事实。 分析结果索引,根据您的需求更改值。 如果需要的话,分步骤进行。 如果查询不为空,请尝试更改de值。

    我实现了更简单、更直接的方法。

    import pandas as pd
    df = pd.DataFrame({'Type':["A","B","A", "C", "A"],'Value':["sesame", None, None, "tea", "bun"]})
    df.loc[df.query("Value!=Value and Type == 'A'").index,'Value'] = 'custard'
    df.loc[df.query("Value!=Value and Type == 'B'").index,'Value'] = 'peanuts'
    df
    
        Type    Value
    --  ------  -------
     0  A       sesame
     1  B       peanuts
     2  A       custard
     3  C       tea
     4  A       bun