[英]Reading Part of a Numpy Array
假設,我有以下數據集作為 numpy 數組:
import numpy as np
x = np.array([0, 5, 10, 15, 20, 25, 30])
y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])
我只想讀取與 x = 20、25、30 對應的值。如何使用 numpy 讀取?
numpy.searchsorted
可以完成這項工作:
idx = np.searchsorted(x,[20,25,30])
part = y[idx]
請注意,必須對x
進行排序。 如果x
未排序,請嘗試:
idx_sort = np.argsort(x)
xsorted = x[idx_sort]
ysorted = y[idx_sort]
idx = np.searchsorted(xsorted, [20,25,30])
part = y[idx]
我們可以使用zip
和list comprehension
過濾y
。
np.array([v for i, v in zip(x, y) if i in [20, 25, 30]])
#array([0.46052632, 0.5 , 0.53947368])
與 pandas 替代。
import pandas as pd
pd.Series(index=x, data=y).loc[[20, 25, 30]].values
此代碼將執行此操作:
import numpy as np
ind = [np.where(x == num)[0] for num in [20, 25, 30]]
corresponding = y[ind]
我相信沒有必要解釋,但如果你需要什么,請評論
使用numpy.any創建 boolean 掩碼的替代方法:
import numpy as np
x = np.array([0, 5, 10, 15, 20, 25, 30])
y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])
values = [20,25,30]
m = np.any([x==v for v in values], axis=0)
y[m]
array([0.46052632, 0.5 , 0.53947368])
不是 numpy 而是一個字典:
import numpy as np
x = np.array([0, 5, 10, 15, 20, 25, 30])
y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])
xy_dict = {}
for j, k in zip(x, y):
xy_dict[j] = k
print(xy_dict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.