我有一个 df 我想在其中转换列中的值b
如果列中的相应值为负数a
is not NaN
.
这是我的代码:
# create a test df
df = pd.DataFrame(np.array([[12, 34], [67, 98], [np.nan, 6], [23, 45], [np.nan, 5], [5, 82], [61, 92]]), columns=['a', 'b'])
print(df)
a b
0 12.0 34.0
1 67.0 98.0
2 NaN 6.0
3 23.0 45.0
4 NaN 5.0
# the code to convert b to negative if a is not NaN
df['b'] = df['b'].apply(lambda x: -x if df['a'] != pd.isnull else x)
这是收到的错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
我试图查找错误代码,但我不明白发生了什么。我正在使用 lambda 但不确定是否有更好的方法。 df 应如下所示:
a b
0 12.0 -34.0
1 67.0 -98.0
2 NaN 6.0
3 23.0 -45.0
4 NaN 5.0