Python中实现Fortran的WHERE语句

2024-10-03 19:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,有没有一种方法可以使用NumPy数组来实现这一点?最好不要使用太多for循环。在

我知道numpy.where()存在,但是如果它可以像下面的Fortran代码片段中那样使用,我不确定如何实现它

z_ocean=0
do i=1,nstep_yr
   where(mldclim(:,:,i).gt.z_ocean) z_ocean = mldclim(:,:,i)
end do

Tags: 方法代码gtnumpyfor数组wheredo
1条回答
网友
1楼 · 发布于 2024-10-03 19:25:38

考虑一下fortran代码中的where语句意味着什么:

分配给z_ocean的每个元素,其中来自mldclim[i, :, :]的对应元素值大于z_ocean中的元素值,mldclim[i, :, :]中的元素值

编辑:我修改了上面的定义,以更好地反映这是一个元素操作的事实,正如@francescalus的评论所述

看一下documentation for ^{},它可以用作where(*condition*, *value if true*, *value if false*)。 所以在你的例子中,是这样的:
z_ocean = np.where(mldclim[i, :, :] > z_ocean, mldclim[i, :, :], z_ocean)

下面是python中的示例(注意,为了直接比较,我在python中交换了索引顺序)

import numpy as np    

nstep_yr = 2    

# initialize randomly
# mldclim = np.random.rand(nstep_yr, 3, 3) - 0.5    
# use these values for fortran comparison
mldclim = np.reshape([ 0.09911714,  0.18911965,  0.30409478, -0.08548523, \
                      -0.03652424, -0.18361127,  0.49970408, -0.04139379, \
                      -0.03451338, -0.24631131,  0.35726568, -0.30630386, \
                       0.26184705,  0.01286879, -0.21745516,  0.46137956, \
                       0.40410629,  0.29996342], (nstep_yr, 3, 3) )    

# initialize and make a copies for testing...
z_ocean = np.zeros((3,3))
z_ocean_1 = np.copy(z_ocean)
z_ocean_2 = np.copy(z_ocean)    

for i in range(nstep_yr):
    # "direct translation" of your fortran code
    z_ocean = np.where(mldclim[i, :, :] > z_ocean, mldclim[i, :, :], z_ocean)
    # loop based version of @francescalus' comment
    z_ocean_1 = np.maximum(z_ocean_1, mldclim[i, :, :])    
# loop free version of @francescalus' comment
z_ocean_2 = np.maximum(z_ocean_2, np.max(mldclim, axis=0)) 

# check that all solutions are the same
assert np.allclose(z_ocean, z_ocean_1) and np.allclose(z_ocean, z_ocean_2)    

print(z_ocean.ravel())

和fortran(复制原始代码示例)

^{pr2}$

其输出如下:

  • python[0.09911714 0.35726568 0.30409478 0.26184705 0.01286879 0. 0.49970408 0.40410629 0.29996342]
  • fortran 9.91171375E-02 0.357265681 0.304094791 0.261847049 1.28687900E-02 0.00000000 0.499704093 0.404106289 0.299963415

相关问题 更多 >