so12311
so12311

Reputation: 4229

numpy negative indexing a[:-0]

I want to use array slicing to trim my array i.e.

a_trimmed = a[trim_left:-trim_right]

this is great, except if trim_right is 0, I get a[trim_left:0], which is an empty array.

I suppose I can could it to

a[trim_left:a.shape[0]-trim_right]

but it's uglier. What's the cleanest way to express this?

Upvotes: 25

Views: 3121

Answers (2)

lanzz
lanzz

Reputation: 43168

None is a valid slice endpoint:

a[trim_left:-trim_right or None]

Upvotes: 43

zhangxaochen
zhangxaochen

Reputation: 34017

It's not that ugly IMHO. the only way I can come up with to make it shorter is replacing a.shape[0] with len(a)

Upvotes: 3

Related Questions