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)?
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]])
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
df.iloc[1::2, :] = df.iloc[1::2, ::-1].values
# ^ ^ ^
# | | Reverse
# Start |
# Every other row
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With