eavsteen - 1 year ago 130

Python Question

I want to get slices from a numpy array and assign them to a larger array.

The slices should be 64 long and should be taken out evenly from the source array.

I tried the following:

`r = np.arange(0,magnitude.shape[0],step)`

magnitudes[counter:counter+len(r),ch] = magnitude[r:r+64]

I get the following error when I tried the above code:

`TypeError: only integer arrays with one element can be converted to an index`

What is the most pythonic way to achieve the slicing?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`magnitude[r:r+64]`

where `r`

is an array is wrong. The variables in the slice must be scalars, `magnitude[3:67]`

, not `magnitude[[1,2,3]:[5,6,7]]`

.

If you want to collect multiple slices you have to do something like

```
In [345]: x=np.arange(10)
In [346]: [x[i:i+3] for i in range(4)]
Out[346]: [array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5])]
In [347]: np.array([x[i:i+3] for i in range(4)])
Out[347]:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
```

Other SO questions have explored variations on this, trying to find the fastest, but it's hard to get around some sort loop or list comprehension.

I'd suggest working with this answer, and come back with a new question, and a small working example, if you think you need more speed.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**