Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse even rows in a numpy array or pandas DataFrame

I have a pandas DataFrame with 400 columns and 100 rows which I would like to display as an image. The instrument that generates these data does so in a way requiring every second row to be reversed for it to be displayed properly.

How can I reverse specific rows in pandas or with numpy if converted to a 2D np.array (i.e. row 1, 3, 5, 7...len(df)?

like image 725
GregW Avatar asked Jun 08 '26 16:06

GregW


2 Answers

If your application is mainly image processing, a pandas DataFrame is probably overkill. Here's an example of one way to reverse every other row of a numpy array. It operates in-place:

In [656]: a
Out[656]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

In [657]: a[1::2, :] = a[1::2, ::-1]

In [658]: a
Out[658]: 
array([[ 0,  1,  2,  3],
       [ 7,  6,  5,  4],
       [ 8,  9, 10, 11],
       [15, 14, 13, 12],
       [16, 17, 18, 19],
       [23, 22, 21, 20]])
like image 184
Warren Weckesser Avatar answered Jun 11 '26 20:06

Warren Weckesser


Setup

import pandas as pd

df = pd.DataFrame([range(5) for _ in range(10)],
                  index=list('abcdefghij'),
                  columns=list('abcde'))

print df

   a  b  c  d  e
a  0  1  2  3  4
b  0  1  2  3  4
c  0  1  2  3  4
d  0  1  2  3  4
e  0  1  2  3  4
f  0  1  2  3  4
g  0  1  2  3  4
h  0  1  2  3  4
i  0  1  2  3  4
j  0  1  2  3  4

Solution and Explanation

df.iloc[1::2, :] = df.iloc[1::2, ::-1].values
#       ^  ^                        ^  
#       |  |                  Reverse
#  Start   |
# Every other row

Demonstration

print df

   a  b  c  d  e
a  0  1  2  3  4
b  4  3  2  1  0
c  0  1  2  3  4
d  4  3  2  1  0
e  0  1  2  3  4
f  4  3  2  1  0
g  0  1  2  3  4
h  4  3  2  1  0
i  0  1  2  3  4
j  4  3  2  1  0
like image 28
piRSquared Avatar answered Jun 11 '26 20:06

piRSquared