You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab用户转Python:基于元素级比较筛选目标数组元素

How to Filter Temperature Values with Element-Wise Comparisons in NumPy

Hey there! Making the switch from MATLAB to Python with NumPy is a great move, and this element-wise filtering problem is super common—let's walk through exactly how to solve it.

First, let's recap your data:

  • Radiation array: rad = [0,0,0,0,0,12,55,95,50,12,60,12,5,0,0,0]
  • Relative humidity array: rhu = [90,91,95,94,93,90,88,89,85,83,81,80,80,85,90,92]
  • Temperature array: tmp = [3,5,6,9,8,9,10,11,13,15,14,13,11,9,8,8]

You want to extract temperature values where radiation > 50 AND relative humidity > 87. Here's how to do this in NumPy:

Step 1: Import NumPy and define your arrays

First, convert your lists into NumPy arrays (NumPy is built for this kind of element-wise operation):

import numpy as np

# Define your arrays as NumPy arrays
rad = np.array([0,0,0,0,0,12,55,95,50,12,60,12,5,0,0,0])
rhu = np.array([90,91,95,94,93,90,88,89,85,83,81,80,80,85,90,92])
tmp = np.array([3,5,6,9,8,9,10,11,13,15,14,13,11,9,8,8])

Step 2: Create element-wise boolean masks

Just like in MATLAB, we'll make boolean arrays (masks) that mark which elements meet each condition:

# Mask for radiation > 50
mask_rad = rad > 50
# Mask for relative humidity > 87
mask_rhu = rhu > 87

If you print these masks, you'll see arrays of True/False values where the condition holds (e.g., mask_rad is True at indices 6,7,10 since those are the positions where rad > 50).

Step 3: Combine the masks and filter the temperature array

We need both conditions to be true, so use the element-wise AND operator & (don't use Python's and—that works for single values, not arrays!). Then use this combined mask to index into the temperature array:

# Combine masks: both conditions must be True
combined_mask = mask_rad & mask_rhu

# Filter the temperature array using the combined mask
filtered_tmp = tmp[combined_mask]

Step 4: Check the result

If you run print(filtered_tmp), you'll get:

[10 11]

Let's verify this:

  • Index 6: rad=55 (>50), rhu=88 (>87) → tmp=10 is included
  • Index7: rad=95 (>50), rhu=89 (>87) → tmp=11 is included
  • Index10: rad=60 (>50), but rhu=81 (<=87) → excluded

That's exactly what we wanted!

Quick note for MATLAB users

This is nearly identical to MATLAB's logical indexing. In MATLAB, you'd write:

filtered_tmp = tmp(rad > 50 & rhu > 87);

NumPy's syntax is very similar—just replace parentheses with square brackets, and ensure you're using NumPy arrays instead of MATLAB matrices.

内容的提问来源于stack exchange,提问作者scana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:47:07