简体   繁体   中英

numpy: why does np.append() flatten my array?

I'm trying to

在 numpy 中复制此功能

replicate this function in numpy

在此处输入图像描述

but for some reason it keeps doing this

在此处输入图像描述

or flattening the array and generally not behaving like i'd expect

在此处输入图像描述

or returning an error

The docstring is very clear. It explains at least three times that:

If axis is None, out is a flattened array.

This is the only reasonable thing to do. If the inputs are multidimensional, but you don't specify which axis to operate on, how can the code determine the "right" axis? For example, what if the input is a square, 2D array? In that case, both axes are equally valid.

There are too many ways for code that tries to be smart about appending to fail, or worse, to succeed but with the wrong results. Instead, the authors decided that flattening is a reasonable default choice, and made that choice explicit in the documentation.

Also note that there is no way to replicate the behavior at the top of your post in NumPy. By definition, ndarray s are rectangular, but the list you have here is "ragged". You cannot have an ndarray where each row or column has different size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM