python why use numpy.r_ instead of concatenate

后端 未结 3 1666
长情又很酷
长情又很酷 2020-12-14 03:00

In which case using objects like numpy.r_ or numpy.c_ is better (more efficient, more suitable) than using fonctions like concatenate or vstack for example ?

I am tr

3条回答
  •  不知归路
    2020-12-14 03:29

    I was also interested in this question and compared the speed of

    numpy.c_[a, a]
    numpy.stack([a, a]).T
    numpy.vstack([a, a]).T
    numpy.column_stack([a, a])
    numpy.concatenate([a[:,None], a[:,None]], axis=1)
    

    which all do the same thing for any input vector a. Here's what I found (using perfplot):

    For smaller numbers, numpy.concatenate is the winner, for larger (from about 3000) stack/vstack.


    The plot was created with

    import numpy
    import perfplot
    
    perfplot.show(
        setup=lambda n: numpy.random.rand(n),
        kernels=[
            lambda a: numpy.c_[a, a],
            lambda a: numpy.stack([a, a]).T,
            lambda a: numpy.vstack([a, a]).T,
            lambda a: numpy.column_stack([a, a]),
            lambda a: numpy.concatenate([a[:, None], a[:, None]], axis=1),
        ],
        labels=["c_", "stack", "vstack", "column_stack", "concat"],
        n_range=[2 ** k for k in range(22)],
        xlabel="len(a)",
        logx=True,
        logy=True,
    )
    

提交回复
热议问题