piRSquared - 1 year ago 170

Python Question

suppose I have the

`pd.Series`

`import pandas as pd`

import numpy as np

s = pd.Series(np.arange(10), list('abcdefghij'))

I'd like to "shuffle" this series like a deck of cards by interweaving the top half with the bottom half.

I'd expect results like this

`a 0`

f 5

b 1

g 6

c 2

h 7

d 3

i 8

e 4

j 9

dtype: int32

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

Answer Source

One way would be to reshape and then use `ravel(order='F')`

to read the items off in Fortran order:

```
In [12]: pd.Series(s.values.reshape(2,-1).ravel(order='F'), s.index)
Out[12]:
a 0
b 5
c 1
d 6
e 2
f 7
g 3
h 8
i 4
j 9
dtype: int64
```

Fortran order makes the left-most axis increment fastest. So in a 2D array the items go down the rows of one column before progressing to the next column. This has the effect of interleaving items, compared to the usual C-order.

Alternatively, you could reshape in Fortran order and ravel in C order:

```
In [17]: s.values.reshape(-1, 2, order='F').ravel()
Out[17]: array([0, 5, 1, 6, 2, 7, 3, 8, 4, 9])
```