【问题标题】:How to print values of a 3 dimensional array that are less than a specific value?如何打印小于特定值的 3 维数组的值?
【发布时间】:2017-07-28 15:27:05
【问题描述】:

所以我有一个名为 data_low 的数据集,如下所示:

(array([ 0,  0,  0, ..., 30, 30, 30]), array([  2,   2,   5, ..., 199, 199, 199]), array([113, 114,  64, ...,  93,  94,  96]))

这是它的形状:(84243,3)。

我可以像这样从数据集中得到一个唯一的降水值:

In [63]: print(data_low[0, 2, 113])
Out [63]: 1.74

我要做的是打印数据集中所有小于 3.86667 的值。我对 python 很陌生,并且真的不知道要使用哪个循环来做到这一点。非常感谢您的帮助。谢谢。

编辑:这是我目前拥有的程序。在某些情况下,我使用 ncecat 组合了 31 个数据集,这就是为什么我有三个一维数组:第一个数组是日期,第二个和第三个表示经度和纬度。

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

latbounds = [ -38 , -20 ]
lonbounds = [ 115 , 145 ] # 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 ]

print(precip_subset.shape)
print(precip_subset.size)
print(np.mean(precip_subset))

data_low = np.nonzero((precip_subset > 0) & (precip_subset < 3.86667))
print(data_low)

x = list(zip(*data_low))[:]
xx = np.array(x)
print(xx.shape)
print(xx.size)

for i in range(0,84243,1):
    print(data_low[i, i, i])

输出:

In [136]: %run "C:\Users\matth\precip_anomalies.py"
(31, 120, 72)
267840
1.51398
(array([ 0,  0,  0, ..., 30, 30, 30]), array([  7,   7,   7, ..., 119, 119, 
119]), array([ 9, 10, 11, ..., 23, 53, 54]))
(13982, 3)
41946
[ 0  0  0 ..., 30 30 30]

TypeErrorTraceback (most recent call last)
C:\Users\matth\precip_anomalies.py in <module>()
     53 
     54 for i in range(0,84243,1):
---> 55     print(data_low[i, i, i])

TypeError: tuple indices must be integers, not tuple

【问题讨论】:

  • 这看起来不像是一个形状为84243x3的数组,而是一个带有三个一维数组的three_tuple。
  • 您想如何打印它们?只是在一个长长的列表中,或者它们的索引,或者剩余的单元格以某种方式“空白”?
  • 我使用 list(zip(*data_low))[:] 然后将其创建为一个 numpy 数组。之后我找到了大小,它是 (84243, 3)

标签: python loops indexing


【解决方案1】:

鉴于 data_low 是一个 numpy 矩阵(根据您的问题,它不是,它是一个包含三个数组的 3 元组),您可以使用掩码:

data_low[data_low < 3.86667]

这将返回一个一维 numpy 数组,其中包含所有小于 3.86667 的值。

如果你想要这些作为一个普通的 Python 列表,你可以使用:

list(data_low[data_low < 3.86667])

但是如果你想做进一步的处理(在 numpy 中)你最好还是使用 numpy 数组。

【讨论】:

  • 我正在考虑做类似“for i in range (0, 84243, 1): print(data_low[ [i], [i], [i] ]),但我一直在错误提示我需要整数值
  • 你为什么用[i]而不是i写它(比如print(data_low[i,i,i]))?此外,您最好尽量减少 Python 级别的调用次数,因为 numpy 更有效。
  • 当我这样做时,它给了我一个错误:“元组索引必须是整数,而不是元组”
  • @MatthewKim:你能用一个重现错误的程序更新你的问题吗?
  • 我贴在上面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多