读取 Numpy 数组的一部分

假设,我有以下数据集作为 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 读取?


HUX布斯
浏览 116回答 5
5回答

潇潇雨雨

我们可以y使用zip和进行过滤list comprehension。np.array([v for i, v in zip(x, y) if i in [20, 25, 30]])#array([0.46052632, 0.5       , 0.53947368])大熊猫的替代品。import pandas as pdpd.Series(index=x, data=y).loc[[20, 25, 30]].values

慕盖茨4494581

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]

HUWWW

另一种使用numpy.any创建布尔掩码的方法:import numpy as npx = 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])

红颜莎娜

此代码将执行此操作:import numpy as npind = [np.where(x == num)[0] for num in [20, 25, 30]]corresponding = y[ind]我相信没有必要解释,但如果你需要什么,请评论

慕的地8271018

不是用 numpy 而是用 dict:import numpy as npx = 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] = kprint(xy_dict)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python