我对 np.where 有一个相当奇怪的问题,这让我怀疑是否应该使用另一个函数。
逻辑如下: 当且仅当“trendup”和“trendown”为“False”时,则为“No_trend”,否则为“trending”
不知怎的,输出是错误的,但我不确定什么是关闭的。
Id Trendup Trendown
0 001 False False
1 002 False False
代码行是:
forecast['trend_status'] = np.where((forecast['Trendup'] == 'False') & (forecast['Trendown'] == 'False'), 'Not_trending', 'trending')
以及错误的输出:
Id Trendup Trendown trend_status
0 001 False False trending
1 002 False False trending
在这种情况下,trend_status 列中应为“Not_trending”,因为前两列为 False。 我猜问题出在 & 声明上。 我看过 np.logic_and() 但似乎这不是我要找的。 欢迎任何帮助
更新: 感谢@Yatu,我已经尝试过:
forecast['trend_status'] = np.where(~(forecast['Trendup'] & forecast['Trendown']), 'Not_trending', 'trending')
但是当我使用数据集来显示一些趋势时,问题仍然存在
0 001 False True Not_trending
1 002 False True Not_trending
可能出了什么问题?我现在已经如此接近这个问题了,以至于我可能看不到显而易见的事情。
最佳答案
问题似乎是您将 bool 值与字符串混淆了。使用 bool 值时,您应该使用 logical operators你应该做类似的事情:
np.where(~(forecast['Trendup'] | forecast['Trendown']), 'Not_trending', 'trending')
# array(['Not_trending', 'Not_trending'], dtype='<U12')
<小时/>
您可以通过以下方式检查情况是否如此:
print(df.dtypes)
Id int64
Trendup bool
Trendown bool
dtype: object
关于python - np.where() 内部存在 & 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60036774/