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

Python 3.6.3中用map处理numpy数组遇TypeError问题求助

Fixing the "TypeError: only integer scalar arrays can be converted to a scalar index" Issue

Let's break down what's happening in your code and how to fix it:

Why the Error Occurs

Your seen variable is a 2D numpy array (shape (3,1)):

seen = np.array([[0,1,0]]).T
# Output: array([[0],
#                [1],
#                [0]])

When map iterates over seen, each x passed to the lambda is a 1-element numpy array (like array([0])), not a plain integer. Python lists (like observations) only accept integer scalars as indices—you can't use an array to index into a list, hence the error.

How to Fix It

You have a few straightforward solutions:

1. Flatten the seen Array

Convert the 2D array to a 1D array so each iteration gives an integer scalar:

import numpy as np

observations = ["red", "white"]
seen = np.array([[0,1,0]]).T

# Use flatten() to get a 1D array
result = list(map(lambda x: observations[x], seen.flatten()))
print(result)  # Output: ['red', 'white', 'red']

2. Extract the Scalar from Each Array Element

Modify your lambda to pull the integer value out of the 1-element array:

result = list(map(lambda x: observations[x[0]], seen))
print(result)  # Output: ['red', 'white', 'red']

3. Use Numpy's Built-in Indexing (More Idiomatic)

Since you're already using numpy, skip map entirely and use numpy's native array indexing:

# Convert observations to a numpy array first, then index
numpy_obs = np.array(observations)
result = numpy_obs[seen.flatten()].tolist()
# Or directly handle the 2D array:
result = numpy_obs[seen].flatten().tolist()
print(result)  # Output: ['red', 'white', 'red']

How to View Map Results

The map object you see (<map at 0x2ab8c869e80>) is an iterator—it doesn't compute results until you iterate over it. To see the actual values, convert it to a list with list(map(...)) (which is what you were trying to do, but the error stopped you). Once you fix the indexing issue, this will work as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:25:49