1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

numpyのndarrayで、マイナスの添字でアクセスすると末尾側からアクセスできます。

末尾にアクセスするときによく-1でアクセスしています。

import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(x[-1])

(出力)

5

-1以外にもアクセスできます。

print(x[-2])

(出力)

4

配列の一つ前の要素からの変化量(=速度)を求めたいとき

スライス表記と合わせて一瞬で配列すべての速度を求められます。

diff = x[1:] - x[:-1]
# ↑ x[1:len(x)] - x[0:len(x)-1] と一緒
print(diff)

(出力)

[1 1 1 1]

2連で使えば

加速度もでますよね

diff = x[1:] - x[:-1]
acc = diff[1:] - diff[:-1]
print(acc)

(出力)

[0 0 0]

らくちんにアクセスできて地味に便利です

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?