社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

fountainhead

fountainhead 最近创建的主题
fountainhead 最近回复了
7 年前
回复了 fountainhead 创建的主题 » 使用另一个list python从list创建索引值数组

假设:

  1. 每一个元素 value_list 将出现在 key_list (在某个位置或另一个位置)
  2. 我们对里面的索引感兴趣 密钥列表 ,只有 第一 比赛

解决方案:

从这两个数组中,我们创建3元组的视图。然后,我们在两个正交方向上广播这两个视图,然后检查广播数组上的元素相等性。

import numpy as np

value_list = np.array([[2,2,3],[255,243,198],[2,2,3],[50,35,3]], dtype='uint8')
key_list   = np.array([[2,2,3],[255,243,198],[50,35,3]], dtype='uint8')

# Define a new dtype, describing a "structure" of 3 uint8's (since
# your original dtype is uint8). To the fields of this structure,
# give some arbitrary names 'first', 'sec', and 'third'
dt = np.dtype([('first', np.uint8, 1),('sec', np.uint8, 1),('third', np.uint8, 1)])

# Now view the arrays as 1-d arrays of 3-tuples, using the dt
v_value_list = value_list.view(dtype=dt).reshape(value_list.shape[0])
v_key_list   = key_list.view(dtype=dt).reshape(key_list.shape[0])

result = np.argmax(v_key_list[:,None] == v_value_list[None,:], axis=0)
print (result)

输出:

[0, 1, 0, 2]

笔记:

  1. 尽管这是一个没有任何可见循环的纯numpy解决方案,但它可能隐藏了低效性,因为它匹配 价值列表 每一个元素 密钥列表 ,而基于循环的搜索则在第一次成功匹配时智能地停止。获得的任何优势将取决于 密钥列表 ,并根据成功匹配的位置, 密钥列表 . 大小为 密钥列表 增长,可能会有一些核优势的侵蚀,特别是如果成功的比赛大多发生在 密钥列表 .

  2. 我们正在创建的视图实际上是numpy结构的数组,其中视图的每个元素都是由两个 int 有一个有趣的问题,我还没有探讨过,当numpy比较一个结构和另一个结构时,它是对结构中的每个字段进行比较,还是在结构的第一个失败字段处使字段比较短路?任何这样的短循环都可能意味着此结构化阵列解决方案有一个小小的附加优势。

7 年前
回复了 fountainhead 创建的主题 » python:从3d numpy数组中的2d数组访问保存的点

这是您拥有的数据:

x_len = 12     # In your case, 1200
y_len = 6      # In your case, 601
z_len = 3      # In your case, 137

import numpy as np
my2d = np.random.randint(0,z_len,(y_len,x_len))
my3d = np.random.randint(0,5,(z_len,y_len,x_len))

这是构建新二维阵列的一种方法:

yindices,xindices = np.indices(my2d.shape)
new2d = my3d[my2d[:], yindices, xindices]

笔记:

  1. 我们正在使用整数高级索引。
  2. 这意味着我们为三维数组编制索引 my3d 有3个整数索引数组。
  3. 有关整数数组索引工作原理的详细说明,请参阅 my answer on this other question
  4. 在你的尝试中,没有必要用 reshape(-1) ,因为我们传递的整数索引数组的形状(在任何广播之后)将成为结果2d数组的形状。
  5. 另外,在您的尝试中,第二个和第三个索引数组需要具有相反的方向。也就是说,它们一定是有形状的 (y_len,1) 和 (1, x_len) . 注意 1 . 这确保了这两个索引数组将被广播