python - 大数组的 if,else 语句

标签 python arrays list numpy list-comprehension

我想在风玫瑰图上绘制风速和风向的一些数据(极地玫瑰图),但我使用的库 (windrose) 似乎不喜欢向它提供负风向。因此,我试图将 360 度添加到所有负值,认为它应该绘制。我尝试执行这篇文章中显示的方法,if else in a list comprehension ,但我的数组中仍然有很多负数。

 wind_speed=np.sqrt(u**2+v**2)
 wind_dir_calc=np.arctan(v/u)
 wind_dir=np.degrees(wind_dir_calc)

 [x+360 if x<0 else x+0 for x in wind_dir]

 np.set_printoptions(threshold=np.inf)
 print(wind_dir)

Sample output:
 [-6.34019175  84.6607632  -58.73626831  55.40771131  73.87242417
 66.70543675  48.0127875   50.71059314  52.27500496  38.15722659
 37.50414236  48.14495746  -2.20259816  16.53483786  38.75162833
 19.0466243  -58.67130713 -63.00416161 -65.41842552 -74.96956948
-74.23281746 -68.36911316 -46.46880071 -83.26398879 -80.75388725...]

最佳答案

你的逻辑是合理的。您只需要将您的列表理解分配给一个变量。列表理解不是就地操作。例如:

wind_dir = [x+360 if x<0 else x+0 for x in wind_dir]

但是,由于您使用的是 NumPy 数组,我建议您使用就地矢量化操作:

wind_dir[wind_dir < 0] += 360

要创建一个新数组,您可以使用numpy.where:

wind_dir = np.where(wind_dir < 0, wind_dir + 360, wind_dir)

关于python - 大数组的 if,else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046762/

相关文章:

list - CloudFormation - 为 List<> 类型设置多个默认值

Python 代理支持通过与错误代理的本地连接

python - 单击时禁用/启用 Tkinter 按钮

ios - append 到数组导致崩溃

java 数组的分割方法

c# - 为什么 IList<>.Reverse() 不像 List<>().Reverse 那样工作

python - 无法在正确位置连接两个列表

python - 使用 ElementTree 时出现未定义实体错误

python - python 模块变量如何工作?

javascript - 在JS中存储用户输入并计算性格测验