在Python中实现Fortran的WHERE语句

时间:2018-06-07 06:58:44

标签: python numpy fortran

有没有办法在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

1 个答案:

答案 0 :(得分:0)

考虑一下你的fortran代码中的where语句含义:

"分配给z_ocean的每个元素,其中mldclim[i, :, :]的相应元素值大于z_ocean中的元素值,mldclim[i, :, :]中的元素值}"

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

查看documentation for numpy.where(),可以将其用作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(复制原始代码示例)

program test
    implicit none

    integer, parameter :: nstep_yr = 2
    real :: mldclim(3,3,nstep_yr)
    real :: z_ocean(3,3)
    integer :: i

    mldclim = 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], [3, 3, 2] )

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

end program test

其中给出了以下输出:

  • 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