【问题标题】:replace non Null values in column by 1将列中的非 Null 值替换为 1
【发布时间】:2015-10-20 00:30:08
【问题描述】:

我有一个数据框,其中有一列如下所示:

note

129.0
130.0
131.0
132.0
133.0
134.0
135.0
136.0
137.0
138.0
139.0
140.0
141.0
142.0

143.0

所以有些行不包含值 (NaN)。 我想将不是 NaN 的数值替换为 1,以具有:

note
1
1
1
1
1
1
1

1

我试过这段代码:

def replace():
    if  (pd.notnull(df['note'])):
        df['note'] = '1'
        return df
    return df

它返回给我ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    为此使用loc

    In [86]:
    df.loc[df['note'].notnull(), 'note'] = 1
    df
    
    Out[86]:
        note
    0      1
    1      1
    2      1
    3      1
    4      1
    5      1
    6      1
    7      1
    8      1
    9      1
    10     1
    11     1
    12     1
    13     1
    14     1
    

    if (pd.notnull(df['note'])) 将不起作用,因为if 不了解如何处理布尔值数组,因此 ValueError 因为您可能在布尔数组中拥有全部 -1 或只有一个 True

    【讨论】:

    • 感谢您像往常一样快速正确地回答@EdChum!
    【解决方案2】:

    您也可以使用where 来实现这一点,就像在就地操作中一样。它将任何不匹配谓词的值设置为指定值。

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'a': ['a', 'b', 'c'], 'note': [145.0, np.NaN, 147.0]})
    df.note.where(df.note.isnull(), 1, inplace=True)
    

    产量

    In [14]: print(df)
    Out[14]: 
       a  note
    0  a     1
    1  b   NaN
    2  c     1
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 2017-10-14
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多