【问题标题】:Getting the position of a value inside a dataset that has three 1D numpy arrays在具有三个 1D numpy 数组的数据集中获取值的位置
【发布时间】:2017-07-31 19:31:14
【问题描述】:

我有一个数据集precip_subset,其中包含三个 1D numpy 数组。我合并了 31 个数据集以创建 precip_subset:数据集中的第一个 numpy 数组表示日期,第二个数组表示经度,第三个数组表示纬度。数据集中每个位置的降水量都有一个唯一值;例如,print(precip_subset[1, 0, 21]) 会给我一个值1.05

precip_subset 中,我只想要具体的降水值。所以我像这样限制了数据集:

 data_low = precip_subset[(precip_subset > 0) & (precip_subset < 3.86667)]

在此之后,我尝试这样做:

for val in data_low:
    if val < 1:
        print(precip_subset.tolist().index(val))

我要做的是获取原始数据集中值的位置,precip_subset。但是,我收到The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 的错误。谁能解释我如何从precip_subset 获取值的位置?

编辑:以下是 precip_subset 的创建方式:

from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

data_path = r"C:\Users\matth\Downloads\TRMM_3B42RT\3B42RT_Daily.201001.7.nc4"
f = Dataset(data_path)

latbounds = [ -31 , -19 ]
lonbounds = [ 131, 146 ] # degrees east ? 
lats = f.variables['lat'][:] 
lons = f.variables['lon'][:]

# latitude lower and upper index
latli = np.argmin( np.abs( lats - latbounds[0] ) )
latui = np.argmin( np.abs( lats - latbounds[1] ) ) 

# longitude lower and upper index
lonli = np.argmin( np.abs( lons - lonbounds[0] ) )
lonui = np.argmin( np.abs( lons - lonbounds[1] ) )

precip_subset = f.variables['precipitation'][ : , lonli:lonui , latli:latui ]

变量“降水”来自原始数据集r"C:\Users\matth\Downloads\TRMM_3B42RT\3B42RT_Daily.201001.7.nc4"

另外,precip_subset 的形状和大小分别是(31, 60, 48)89280

【问题讨论】:

  • 不太清楚precip_subset 是如何创建的……它通过质押三个一维数组创建了什么?这应该会产生一个 2D 数组,这与您的用法示例 precip_subset[1, 0, 21]) 相矛盾,这表明 precip_subset 是一个 3D 数组。因此,请澄清您的precip_subsetarray 的形状。
  • 我会发布我的整个代码。
  • 我认为创建一个代表您的数据的 numpy 数据数组的小示例会更有帮助。您的示例未显示文件中数据的排列方式,需要熟悉 netCDF4 才能回答您的问题。

标签: python numpy indexing


【解决方案1】:

您可以尝试以下方法(假设我从您的示例中正确理解了这个想法):

data_low_indices1 = np.where((precip_subset > 0) & (precip_subset < 3.86667))

这将返回条件成立的一维索引数组的元组。您可能需要转置此列表:

data_low_indices2 = np.array(np.where((precip_subset > 0) & (precip_subset < 3.86667))).T

那么你可以:

for ind in data_low_indices2:
    print(ind)

如果您不想转置,请执行以下操作:

for ind in zip(*data_low_indices1):
    print(ind)

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2021-02-08
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多