簡體   English   中英

提取數組中的每個第3個數據

[英]Extracting every 3rd data in an array

我有數千個x和y數據,對於這種情況,我將只使用12個數據。 該數組用於繪制圖形

x = np.array([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000])
y = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
py.plot(x,y)

我如何提取每個[3]乘法我的情節? 例如

x = np.array([3000,6000,9000,12000])
y = np.array([3,6,9,12])
py.plot(x,y)

我怎樣才能為每個[5]乘法提取情節? 例如

x = np.array([5000,10000])
y = np.array([5,10])
py.plot(x,y)

從第三個項目(一維數組)開始提取每三個項目

x[2::3], y[2::3]

從第五個項目(一維數組)開始提取每五個項目

x[4::5], y[4::5]

如果您只是詢問如何提取每個第x個項目,切片接受步驟參數以及開始和停止。

例如:

In [1]: import numpy as np

In [2]: np.arange(10)
Out[2]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: x = np.arange(10)

In [4]: x[::2]
Out[4]: array([0, 2, 4, 6, 8])

In [5]: x[::3]
Out[5]: array([0, 3, 6, 9])

In [6]: x[3::3]
Out[6]: array([3, 6, 9])

如果你問如何找到偶數倍,你可以使用布爾索引。

例如:

In [7]: x[x % 3 == 0]
Out[7]: array([0, 3, 6, 9])

使用numpy.where

>>> x = np.array([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000])
>>> y = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
>>> idxs = np.where(x % 3 == 0)
>>> x[idxs]
array([ 3000,  6000,  9000, 12000])
>>> y[idxs]
array([ 3,  6,  9, 12])

>>> x[x % 3 == 0]
array([ 3000,  6000,  9000, 12000])

使用返回限定值的函數。 例如:

def filter_indices(lst, value):
    return [v for _, v in enumerate(lst) if v % value == 0]

結果:

>>> filter_indices(l, 3)
[3, 6, 9, 12]

或者,使用np.where函數:

indices = np.where(x % 3 == 0)
py.plot(x[indices], y[indices])

暫無
暫無

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

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