将列中的非 Null 值替换为 1

4 python dataframe pandas

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

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
Run Code Online (Sandbox Code Playgroud)

因此有些行不包含值 (NaN)。我想将非 NaN 的数值替换为 1,以获得:

note
1
1
1
1
1
1
1

1
Run Code Online (Sandbox Code Playgroud)

我尝试了这段代码:

def replace():
    if  (pd.notnull(df['note'])):
        df['note'] = '1'
        return df
    return df
Run Code Online (Sandbox Code Playgroud)

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

EdC*_*ica 5

用于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
Run Code Online (Sandbox Code Playgroud)

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