【问题标题】:How do I make a for loop to each individual array?如何为每个单独的数组创建一个 for 循环?
【发布时间】:2020-11-20 11:16:28
【问题描述】:

我创建了一个函数,我希望使用 for 循环或其他方法将该函数应用于这些不同的值。 如何创建一个获取每个值但将它们存储在不同数组中的 for 循环?

到目前为止我有这个:

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.patches as patches 
import xarray as xr 
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import netCDF4 as s
import numpy.ma as ma

fwf_tot = fwf_ice      + ds.runoff_tundra*ds.LSMGr #data input i am using 


# function i want to apply to the data

def ob_annual(ob_monthly, id_number):
    ann_sum =  ob_monthly.where(ds.ocean_basins == id_number).resample(TIME='1AS').sum().sum(dim=('X','Y'))
    return ann_sum 

这就是我的问题是创建 for 循环以保存这些不同的值。我认为这个 for 循环只是保存应用于最后一个值(87)而不是其他值的函数。我该如何解决这个问题?我预计会有 7 个数组的输出,每个数组的大小为 59。

obs = np.array([26,28,29,30,76,84,87])

total_obs = []

for i in obs:
    total_obs = ob_annual(fwf_tot_grnl, i)
    
print(total_obs.shape) 

(59)

【问题讨论】:

    标签: python numpy jupyter


    【解决方案1】:

    您在每次迭代时替换您的列表total_obs。您必须将每个值附加到其中:

    for i in obs:
        total_obs.append(ob_annual(fwf_tot_grnl, i))
    

    或使用理解列表

    total_obs = [ob_annual(fwf_tot_grnl, i) for i in obs]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-30
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      相关资源
      最近更新 更多