user3338505 user3338505 - 1 year ago 88
Python Question

Slice 1D Array in Numpy without loop

I have a array

as shown below:

"83838384848411A926791C162048204820484D4444C3BF"], dtype=object)

These are concatenated hex values that I need to slice in order to convert to integers and then apply conversion factors. I want an array such as:


Which would be the equivalent of
but I cannot slice in this
array. I am trying to do something similar to what a character array would do in MatLab. I will be doing this over millions of rows which is why I am trying to avoid a loop.

Answer Source

If you're just after the first two characters from each hex value, one option is to recast your array to a dtype of '|S2':

>>> x.astype('|S2')
array(['83', '83', '83', '84', '84', '84', '83', '85', '85', '83'], 

This idea can be generalised to return the first n characters from each string.

Arbitrary slicing of string arrays is much more difficult to do in NumPy. Answers on this Stack Overflow page explain why it isn't the best tool for strings but show what can be possible.

Alternatively, the Pandas library facilitates fast vectorized operations (being built on top of NumPy). It has a number of very useful string operations which makes slicing a whole lot simpler than plain NumPy:

>>> import pandas as pd
>>> s = pd.Series(x)
>>> s.str.slice(2, 9)
0    8383747
1    83835F6
2    8383848
3    84835C5
4    8484787
5    8484505
6    8383757
7    8484555
8    8584535
9    8383848
dtype: object
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download