Python 将列中的非空值替换为1

Python 将列中的非空值替换为1,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个dataframe,它有一个列,如下所示: 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'])):

我有一个dataframe,它有一个列,如下所示:

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:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。
为此使用
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
值您也可以使用
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

感谢您像往常一样快速正确地回答@EdChum!