gpt4 book ai didi

python - 在Python中实现Fortran的WHERE语句

转载 作者:行者123 更新时间:2023-12-01 09:22:06 24 4
gpt4 key购买 nike

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

最佳答案

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

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

的元素值

编辑: 我修改了上面的定义,以更好地反射(reflect)这是一个元素操作的事实,如 @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

关于python - 在Python中实现Fortran的WHERE语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com