给出以下DataFrame:
d = {'A': [1,2,np.nan, -2, -1], 'B':[5,-1,np.nan,2,-1], 'C':[1,2,3,4,-1]}
df = pd.DataFrame(d)
我需要用np.nan(例如)替换B列中小于0的所有值;我试过了:
df = df.apply(lambda x: fillna(value = np.nan) if x < 0)
但是它给了我以下错误:
File "<ipython-input-157-2d34a150c603>", line 1
df = df.apply(lambda x: fillna(value = np.nan) if x < 0)
SyntaxError: invalid syntax
答案 0 :(得分:0)
试试这段代码:
for i in range (0,len(df.columns)):
x=df.columns[i]
df[df[x]<0]=np.nan
答案 1 :(得分:0)
将pd.DataFrame.loc
与掩码一起使用:
df.loc[df['B'] < 0, 'B'] = np.nan
print(df)
A B C
0 1.0 5.0 1
1 2.0 NaN 2
2 NaN NaN 3
3 -2.0 2.0 4
4 -1.0 NaN -1