簡體   English   中英

使用 numpy 數組的切片索引

[英]slice index using numpy array

考慮以下代碼:

import numpy as np
np.random.seed(0)

x = np.random.randint(0,9,(10,10,3))
x[np.array([0,1]):np.array([5,6])]

我收到以下錯誤:

TypeError: only integer scalar arrays can be converted to a scalar index

我想我需要解壓索引為x的 arrays,但由於*不起作用,所以無法找到解決方法。

目標是讓x[0:5]x[1:6]

編輯

由於要求,我在這里發布了我正在尋找的問題的解決方案:

import numpy as np
np.random.seed(0)

x = np.random.randint(0,9,(10,10,3))
arr1,arr2 = np.array([0,1]),np.array([5,6])

slices = []
for i,j in zip(arr1,arr2):
    slices.append(x[i:j])

print(slices)

這樣我就可以按要求擁有兩個切片,即x[0:5]x[1:6] 如果有人知道如何在沒有 for 循環的情況下解決這個問題,那將非常有幫助。 謝謝。

這是另一個,

import numpy as np
np.random.seed(0)

x = np.random.randint(0,9,(10,10,3))
[x[i:j] for i,j in zip(np.array([0,1]),np.array([5,6]))]

如果我理解正確的問題,你不應該在x[np.array([0,1]):np.array([0,1])]中使用“:”

使用 "," 代替x[np.array([0,1]),np.array([0,1])]

您可以生成類似於此答案的索引數組。

import numpy as np

x = np.random.randint(0,9,(10,10,3))
idcs = np.array([
    np.arange(0,5),
    np.arange(1,6),
])

print(x.shape)
# (10, 10, 3)
print(x[idcs].shape)
# (2, 5, 10, 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM