如何在 Python 中声明和填充数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25042214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare and fill an array in Python?
提问by handroski
I need to create an empty array in Python and fill it in a loop method.
我需要在 Python 中创建一个空数组并用循环方法填充它。
data1 = np.array([ra,dec,[]])
data1 = np.array([ra,dec,[]])
Here is what I have. The ra and dec portions are from another array I've imported. What I am having trouble with is filling the other columns. Example. Lets say to fill the 3rd column I do this:
这是我所拥有的。ra 和 dec 部分来自我导入的另一个数组。我遇到的问题是填充其他列。例子。假设要填写第 3 列,我这样做:
for i in range (0,56):
data1[i,3] = 32
The error I am getting is:
我得到的错误是:
IndexError: invalid index for the second line in the aforementioned code sample.
IndexError:上述代码示例中第二行的索引无效。
Additionally, when I check the shape of the array I created, it will come out at (3,). The data that I have already entered into this is intended to be two columns with 56 rows of data.
此外,当我检查我创建的数组的形状时,它会在(3,). 我已经输入的数据是两列,有 56 行数据。
So where am I messing up here? Should I transpose the array?
那么我在哪里搞砸了?我应该转置数组吗?
采纳答案by deinonychusaur
You could do:
你可以这样做:
data1 = np.zeros((56,4))
to get a 56 by 4 array. If you don't like to start the array with 0, you could use np.onesor np.emptyor np.ones((56, 4)) * np.nan
得到一个 56 x 4 的数组。如果你不喜欢下手的数组0,你可以使用np.ones或np.empty或np.ones((56, 4)) * np.nan
Then, in most cases it is best not to python-loop if not needed for performance reasons. So as an example this would do your loop:
然后,在大多数情况下,如果出于性能原因不需要,最好不要使用 python-loop。因此,作为示例,这将执行您的循环:
data[:, 3] = 32
回答by Eelco Hoogendoorn
data1 = np.array([ra,dec,[32]*len(ra)])
Gives a single-line solution to your problem; but for efficiency, allocating an empty array first and then copying in the relevant parts would be preferable, so you avoid the construction of the dummy list.
为您的问题提供单行解决方案;但是为了效率,最好先分配一个空数组,然后再复制相关部分,这样可以避免构建虚拟列表。
回答by Peter
Assuming ra and dec are vectors (1-d):
假设 ra 和 dec 是向量(1-d):
data1 = np.concatenate([ra[:, None], dec[:, None], np.zeros((len(ra), 1))+32], axis=1)
Or
data1 = np.empty((len(ra), 3))
data[:, 0] = ra
data[:, 1] = dec
data[:, 2] = 32
回答by punyidea
One thing that nobody has mentioned is that in Python, indexing starts at 0, not 1.
没有人提到的一件事是,在 Python 中,索引从 0 开始,而不是 1。
This means that if you want to look at the third column of the array, you actually should address [:,2], not [:,3].
这意味着如果您想查看数组的第三列,您实际上应该是 address [:,2],而不是[:,3]。
Good luck!
祝你好运!

