重复数组的每一个值的两倍(numpy的) [英] Repeat each value of an array two times (numpy)

查看:855
本文介绍了重复数组的每一个值的两倍(numpy的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A 是一个numpy的阵列,如:

  A = np.array([1,2,3,4,5])

我想找到生产与每个值的新阵列的更清洁的方式重复两次:

  B = np.array([1,1,2,2,3,3,4,4,5,5])

你觉得这是做的更简单的方法?

 导入numpy的是NP
B = np.tile(A,2).reshape(2,-1).flatten(F)


解决方案

您可以使用 numpy.column_stack numpy.ndarray.flatten

  [12]:numpy.column_stack((A,A))压平()
出[12]:阵列([1,1,2,2,3,3,4,4,5,5])

时间比较:

 在[27]:A = numpy.array([1,2,3,4,5] * 1000)在[28]:%timeit numpy.column_stack((A,A))压平()
10000循环,最好的3:每圈44.7微秒在[29]:%timeit numpy.repeat(A,2)
10000循环,最好的3:每回路104微秒在[30]:%timeit numpy.tile(A,2).reshape(2,-1).flatten(F)
10000循环,最好的3:每回路129微秒

Let A be a numpy array like :

A = np.array([1, 2, 3, 4, 5])

I want to find the cleaner way to produce a new array with each value repeated two times:

B = np.array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])

Do you think this is the simpler way to do it ?

import numpy as np
B = np.tile(A,2).reshape(2,-1).flatten('F')

解决方案

You can use numpy.column_stack and numpy.ndarray.flatten:

In [12]: numpy.column_stack((A, A)).flatten()                                                    
Out[12]: array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])

Timing comparison:

In [27]: A = numpy.array([1, 2, 3, 4, 5]*1000)                                                   

In [28]: %timeit numpy.column_stack((A, A)).flatten()                                            
10000 loops, best of 3: 44.7 µs per loop                                                         

In [29]: %timeit numpy.repeat(A, 2)                                                              
10000 loops, best of 3: 104 µs per loop                                                          

In [30]: %timeit numpy.tile(A,2).reshape(2,-1).flatten('F')                                      
10000 loops, best of 3: 129 µs per loop     

这篇关于重复数组的每一个值的两倍(numpy的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆