2

Is df.reindex(columns=reversed(df.columns)) the fastest way to reverse a pandas.DataFrame by column?

hygull
  • 8,464
  • 2
  • 43
  • 52
boboo
  • 105
  • 12
  • 1
    Related: [What is the Big O Complexity of Reversing the Order of Columns in Pandas DataFrame?](https://stackoverflow.com/q/51486063/9209546) – jpp Jan 21 '19 at 15:56

2 Answers2

3

One idea - use DataFrame.iloc with indexing:

df = df.iloc[:, ::-1]

Performance:

np.random.seed(234)

df = pd.DataFrame(np.random.randint(10, size=(3, 10000))).rename(columns=str)
#print (df)

In [225]: %timeit df.reindex(columns=reversed(df.columns))
7.32 ms ± 166 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [226]: %timeit df.iloc[:, ::-1]
132 µs ± 6.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

#vdkotian solution
In [227]: %timeit df[df.columns[::-1]]
2.84 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Just tried on sample dataset.

sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa
5           5.4          3.9           1.7          0.4  setosa
6           4.6          3.4           1.4          0.3  setosa
7           5.0          3.4           1.5          0.2  setosa
8           4.4          2.9           1.4          0.2  setosa
9           4.9          3.1           1.5          0.1  setosa

>>> df[df.columns[::-1]]


species  petal_width  petal_length  sepal_width  sepal_length
0  setosa          0.2           1.4          3.5           5.1
1  setosa          0.2           1.4          3.0           4.9
2  setosa          0.2           1.3          3.2           4.7
3  setosa          0.2           1.5          3.1           4.6
4  setosa          0.2           1.4          3.6           5.0
5  setosa          0.4           1.7          3.9           5.4
6  setosa          0.3           1.4          3.4           4.6
7  setosa          0.2           1.5          3.4           5.0
8  setosa          0.2           1.4          2.9           4.4
9  setosa          0.1           1.5          3.1           4.9

df.column[::-1] reverses the order of the dataframe in sequence of column and df[..] re-indexes it.

A more succinct way to achieve the same thing is with the iloc indexer:

df.iloc[:, ::-1]

The first : means "take all rows", the ::-1 means step backwards through the columns.

for reference see link https://stackoverflow.com/questions/27817718/reverse-dataframe-column-order

vdkotian
  • 539
  • 6
  • 13