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

如何创建包含不同数据类型的结构化NumPy数组

Got it, let's fix this to make your code cleaner and reusable!

The key is to define a structured NumPy dtype that matches your desired columns, then convert your byte-encoded data directly into this structured array in one go. Here's how to do it step by step:

Step 1: Define the structured dtype

First, specify the data types for each field you care about—id (integer), datetime (we'll use NumPy's efficient datetime64 type), and anomaly_length (integer):

import numpy as np

# Define the structured data type
structured_dtype = [
    ('id', int),
    ('datetime', 'datetime64[ns]'),
    ('anomaly_length', int)
]

Step 2: Decode byte data and create the structured array

Your raw data has byte strings (like b'1'), so we first decode each element to regular strings, then feed this into np.array with our defined dtype:

# Decode byte columns to strings for all rows (skip the header row)
decoded_rows = [[col.decode('utf-8') for col in row] for row in data[1:, 0:3]]

# Create the structured array in one line
structured_data = np.array(decoded_rows, dtype=structured_dtype)

Step 3: Use the structured array in your function

Now you can pass the structured array (or its individual fields) directly to special_find without repeating conversions. For example:

# Access individual fields by name (no more separate arrays!)
special_find(structured_data['id'], structured_data['datetime'], structured_data['anomaly_length'])

Bonus: Even simpler if reading directly from CSV

If you haven't already loaded the CSV into data, you can skip the manual byte handling entirely by reading directly into a structured array with np.genfromtxt:

structured_data = np.genfromtxt(
    'your_file.csv',
    delimiter=',',
    skip_header=1,  # Skip the first row (headers)
    dtype=structured_dtype,
    usecols=(0, 1, 2)  # Only load the columns we need
)

This approach keeps your code concise, avoids redundant conversions, and makes special_find calls much cleaner—perfect for repeated use!

内容的提问来源于stack exchange,提问作者wake-0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:12:32