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

如何将含逗号分隔字符串的列表转为指定结构的numpy浮点型多维数组?

Solution to Convert String List to Target Numpy Array

Hey there! Let's fix this problem step by step. The core issue here is your original list contains comma-separated strings—we need to first split those strings into individual numeric values, convert them to integers (or floats), then reshape the array to match your desired structure. Here's the proper way to do it:

Step-by-Step Breakdown

  • Split & convert each string: Iterate through your list, split every comma-separated string into parts, and convert each part to an integer.
  • Convert to numpy array: Turn the processed nested list into a numpy array—this will lock in the integer type automatically.
  • Reshape to target structure: Adjust the array's dimensions to get the [[[11],[2019]],[[12],[2019]]] shape you need.

Working Code Example

import numpy as np

# Your original input list
original_list = ['11,2019', '12,2019']

# Step 1: Split strings and convert to integers
processed_data = [[int(num) for num in item.split(',')] for item in original_list]

# Step 2: Convert to a numpy integer array
base_array = np.array(processed_data)

# Step 3: Reshape to the 3D structure you want (shape: (2, 2, 1))
target_array = base_array.reshape(2, 2, 1)

print(target_array)
# Output:
# array([[[  11],
#         [2019]],
# 
#        [[  12],
#         [2019]]])

Why Your Previous Attempts Failed

  • Using reshape directly on the original string array only changes the shape, not the content—you still end up with string elements, just arranged differently.
  • Trying int(arr) threw an error because int() can only convert a single string/number, not an entire list. You have to process each string element individually first.

Alternative Numpy-Centric Method

If you prefer a more numpy-focused approach, you can use np.fromstring to parse each string directly:

import numpy as np

original_list = ['11,2019', '12,2019']

# Parse each string into an integer array, then combine into a single array
base_array = np.array([np.fromstring(s, sep=',', dtype=int) for s in original_list])
target_array = base_array.reshape(-1, 2, 1)  # -1 lets numpy auto-infer the first dimension

Both methods will give you the exact 3D integer array you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:28:33