pandas DataFrame set value on boolean mask

前端 未结 4 1239
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 20:07

I\'m trying to set a number of different in a pandas DataFrame all to the same value. I thought I understood boolean indexing for pandas, but I haven\'t found any resources

4条回答
  •  我在风中等你
    2020-12-18 20:40

    You can't use the boolean mask on mixed dtypes for this unfortunately, you can use pandas where to set the values:

    In [59]:
    df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
    mask = df.isin([1, 3, 12, 'a'])
    df = df.where(mask, other=30)
    df
    
    Out[59]:
        A   B
    0   1   a
    1  30  30
    2   3  30
    

    Note: that the above will fail if you do inplace=True in the where method, so df.where(mask, other=30, inplace=True) will raise:

    TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value

    EDIT

    OK, after a little misunderstanding you can still use where y just inverting the mask:

    In [2]:    
    df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
    mask = df.isin([1, 3, 12, 'a'])
    df.where(~mask, other=30)
    
    Out[2]:
        A   B
    0  30  30
    1   2   b
    2  30   f
    

提交回复
热议问题