在数组的开头添加元素,并在numpy的末尾删除 [英] Add element at the start of array and delete at the end numpy

查看:145
本文介绍了在数组的开头添加元素,并在numpy的末尾删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy数组的开头添加新元素并删除该数组的最后一个元素的最佳方法是什么?

我使用了这样的代码:

tmp = np.array([1,2,3])
print(tmp)
tmp = np.insert(tmp,0,0)
tmp = np.delete(tmp,-1)
print(tmp)

所以我得到了想要的东西:

[1 2 3]
[0 1 2]

但是我怀疑还有更好的方法.

解决方案

一种更清洁的方式来做您正在做的事情:

tmp = np.insert(tmp[0:-1], 0, 0)

tmp = np.append([0], tmp[0:-1])

tmp = np.concatenate(([0], tmp[0:-1]))

如果要插入数组中的特定位置,则.insert是干净的方法,但是如果您的要求是在第0个位置(或末尾)添加元素,则连接可能会更有效.

一个简单的timeit检查可以显示每个循环的2.07 µs,连接的每个5.47 µs和插入的每个12.7 µs(这不是测量时间的理想方法,但可以给出粗略的估计) /p>

What is the best way to add a new element at the start of numpy array and delete the last element of this array ?

I used code like this :

tmp = np.array([1,2,3])
print(tmp)
tmp = np.insert(tmp,0,0)
tmp = np.delete(tmp,-1)
print(tmp)

So I got what I wanted:

[1 2 3]
[0 1 2]

But I suspect that there is a better way to do this.

解决方案

A cleaner way to do what you are doing:

tmp = np.insert(tmp[0:-1], 0, 0)

or

tmp = np.append([0], tmp[0:-1])

or

tmp = np.concatenate(([0], tmp[0:-1]))

If you want to insert at a specific position in the array then .insert is clean approach but if your requirements are to add an element at 0th position(or end) then concatenate might be more efficient.

A simple timeit check reveals 2.07 µs per loop for concatenate, 5.47 µs per loop for append and 12.7 µs per loop for insert(this is not the perfect way of measuring time but it gives a rough estimate)

这篇关于在数组的开头添加元素,并在numpy的末尾删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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