python字符串数组切片性能,动态Python数组切片

I am facing a situation where I have a VERY large numpy.ndarray (really, it's an hdf5 dataset) that I need to find a subset of quickly because they entire array cannot be held in memory. However, I also do not want to iterate through such an array (even declaring the built-in numpy iterator throws a MemoryError) because my script would take literally days to run.

As such, I'm faced with the situation of iterating through some dimensions of the array so that I can perform array-operations on pared down subsets of the full array. To do that, I need to be able to dynamically slice out a subset of the array. Dynamic slicing means constructing a tuple and passing it.

For example, instead of

my_array[0,0,0]

I might use

my_array[(0,0,0,)]

Here's the problem: if I want to slice out all values along a particular dimension/axis of the array manually, I could do something like

my_array[0,:,0]

> array([1, 4, 7])

However, I this does not work if I use a tuple:

my_array[(0,:,0,)]

where I'll get a SyntaxError.

How can I do this when I have to construct the slice dynamically to put something in the brackets of the array?

解决方案

You could slice automaticaly using python's slice:

>>> a = np.random.rand(3, 4, 5)

>>> a[0, :, 0]

array([ 0.48054702, 0.88728858, 0.83225113, 0.12491976])

>>> a[(0, slice(None), 0)]

array([ 0.48054702, 0.88728858, 0.83225113, 0.12491976])

The slice method reads as slice(*start*, stop[, step]). If only one argument is passed, then it is interpreted as slice(0, stop).

In the example above : is translated to slice(0, end) which is equivalent to slice(None).

Other slice examples:

:5 -> slice(5)

1:5 -> slice(1, 5)

1: -> slice(1, None)

1::2 -> slice(1, None, 2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值