gpt4 book ai didi

python - 将单例维度添加到 NumPy 向量以便切片分配工作的有效方法

转载 作者:IT老高 更新时间:2023-10-28 20:50:06 24 4
gpt4 key购买 nike

在 NumPy 中,如何有效地将 1-D 对象转换为 2-D 对象,其中从当前对象推断出单一维度(即列表应该转到 1xlength 或 lengthx1 向量)?

 # This comes from some other, unchangeable code that reads data files.
my_list = [1,2,3,4]

# What I want to do:
my_numpy_array[some_index,:] = numpy.asarray(my_list)

# The above doesn't work because of a broadcast error, so:
my_numpy_array[some_index,:] = numpy.reshape(numpy.asarray(my_list),(1,len(my_list)))

# How to do the above without the call to reshape?
# Is there a way to directly convert a list, or vector, that doesn't have a
# second dimension, into a 1 by length "array" (but really it's still a vector)?

最佳答案

在最一般的情况下,向数组添加额外维度的最简单方法是在索引位置以添加额外维度时使用关键字None。例如

my_array = numpy.array([1,2,3,4])

my_array[None, :] # shape 1x4

my_array[:, None] # shape 4x1

关于python - 将单例维度添加到 NumPy 向量以便切片分配工作的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9510252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com