让我再编辑一次我的问题.我知道flatten是如何工作的,但我正在寻找是否有可能移除inside braces和简单的two outside braces,就像MATLAB中一样,并保持相同的shape of (3,4).这里是arrays inside array,我想要只有一个数组,这样我就可以很容易地绘制它,并得到与Matlab相同的结果. 例如,我有下面的matrix(它是数组中的数组):

s=np.arange(12).reshape(3,4)
print(s)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

有没有可能是reshapeflatten(),然后得到这样的结果:

[ 0  1  2  3
  4  5  6  7
  8  9 10 11]

推荐答案

第一个答案

如果我正确理解了您的问题(其他4个答案说我没有),您的问题不是如何对数组进行flatten()reshape(-1),而是如何确保即使在reshape 之后,它仍然以每行4个元素显示.

严格地说,我认为你做不到.数组只是一堆元素.它们不包含我们想要如何看到它们的指示.这是一个打印问题,你应该在打印的时候解决.你可以看到[这里][1]想要这样做的人……从在2D中reshape 数组开始.

也就是说,在不创建自己的打印函数的情况下,您可以使用np.set_printoptions控制NumPy显示数组的方式.

尽管如此,它仍然很棘手,因为该函数只允许您指定每行打印多少个字符,而不是元素.因此,您需要知道每个元素需要多少个字符才能强制换行.

在您的示例中:

np.set_printoptions(formatter={"all":lambda x:"{:>6}".format(x)}, linewidth=7+(6+2)*4)

格式化程序确保每个数字使用6个字符. 考虑到"数组(["部分,以及结束的"])"(9个字符)加上每个元素之间的2",",知道我们需要4个元素,行宽必须是9+6×4+2×3:9个字符,表示"array[...]",6×4表示每4个数字,2×3表示每个3","分隔符.或7+(6+2)×4.

您只能使用它进行一次打印

with np.printoptions(formatter={"all":lambda x:"{:>6}".format(x)}, linewidth=7+(6+2)*4):
    print(s.reshape(-1))

一段时间后编辑:子类

我想到的另一种方法是将ndarray子类,使其行为符合您的要求

import numpy as np


class MyArr(np.ndarray):
# To create a new array, with args ls: number of element to print per line, and arr, normal array to take data from
    def __new__(cls, ls, arr):
        n=np.ndarray.__new__(MyArr, (len(arr,)))
        n.ls=ls
        n[:]=arr[:]
        return n

    def __init__(self, *args):
        pass

    # So that this .ls is viral: when ever the array is created from an operation from an array that has this .ls, the .ls is copyied in the new array
    def __array_finalize__(self, obj):
        if not hasattr(self, 'ls') and type(obj)==MyArr and hasattr(obj, 'ls'):
            self.ls=obj.ls

    # Function to print an array with .ls elements per line
    def __repr__(self):
        # For other than 1D array, just use standard representation
        if len(self.shape)!=1:
            return super().__repr__()

        mxsize=max(len(str(s)) for s in self)
        s='['
        for i in range(len(self)):
            if i%self.ls==0 and i>0:
                 s+='\n '
            s+=f'{{:{mxsize}}}'.format(self[i])
            if i+1<len(self): s+=', '
        s+=']'
        return s

现在您可以使用这MyArr来构建您自己的一维数组

MyArr(4, range(12))

展示会

[ 0.0,  1.0,  2.0,  3.0, 
  4.0,  5.0,  6.0,  7.0, 
  8.0,  9.0, 10.0, 11.0]

你可以在任何1D ndarray合法的地方使用它.在大多数情况下,.ls属性会跟在后面(我说"大多数时候",因为我不能保证某些函数不会构建一个新的ndarray,并用这个ndarray中的数据填充它们)

a=MyArr(4, range(12))
a*2
#[ 0.0,  2.0,  4.0,  6.0, 
#  8.0, 10.0, 12.0, 14.0, 
# 16.0, 18.0, 20.0, 22.0]
a*a
#[  0.0,   1.0,   4.0,   9.0, 
#  16.0,  25.0,  36.0,  49.0, 
#  64.0,  81.0, 100.0, 121.0]
a[8::-1]
#[8.0, 7.0, 6.0, 5.0, 
# 4.0, 3.0, 2.0, 1.0, 
# 0.0]

# It even resists reshaping
b=a.reshape((3,4))
b
#MyArr([[ 0.,  1.,  2.,  3.],
#       [ 4.,  5.,  6.,  7.],
#       [ 8.,  9., 10., 11.]])
b.reshape((12,))
#[ 0.0,  1.0,  2.0,  3.0, 
#  4.0,  5.0,  6.0,  7.0, 
#  8.0,  9.0, 10.0, 11.0]

# Or fancy indexing
a[np.array([1,2,5,5,5])]
#[1.0, 2.0, 5.0, 5.0,
# 5.0]


# Or matrix operations
M=np.eye(12,k=1)+2*M.identity(12) # Just a matrix
M@a
#[ 1.0,  4.0,  7.0, 10.0, 
# 13.0, 16.0, 19.0, 22.0, 
# 25.0, 28.0, 31.0, 22.0]
np.diag(M*a)
#[ 0.0,  2.0,  4.0,  6.0, 
#  8.0, 10.0, 12.0, 14.0, 
# 16.0, 18.0, 20.0, 22.0]

# But of course, some time you loose the MyArr class
import pandas as pd
pd.DataFrame(a, columns=['v']).v.values
#array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])

  [1]: https://stackoverflow.com/questions/25991666/how-to-efficiently-output-n-items-per-line-from-numpy-array

Python相关问答推荐

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

在Pandas DataFrame操作中用链接替换'方法的更有效方法

从dict的列中分钟

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

跳过嵌套JSON中的级别并转换为Pandas Rame

如何删除重复的文字翻拍?

提取数组每行的非零元素

裁剪数字.nd数组引发-ValueError:无法将空图像写入JPEG

Python OPCUA,modbus通信代码运行3小时后出现RuntimeError

比较两个有条件的数据帧并删除所有不合格的数据帧

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?

如何获取给定列中包含特定值的行号?

使用Scikit的ValueError-了解

大Pandas 中的群体交叉融合

对当前的鼹鼠进行编码,并且我的按键获得了注册

多个布尔条件的`jax.lax.cond`等效项

IpyWidget Select 框未打开

as_index=False groupBy不支持count

如何在polars group_by中将多个行分组到列表中

对齐多个叠置多面Seborn CAT图