Feature Type

  • [X] Adding new functionality to pandas

  • [ ] Changing existing functionality in pandas

  • [ ] Removing existing functionality in pandas

Problem Description

One day while doing some routine stuff with pandas, I was chaining a couple of methods to transform a DataFrame. However, I ended up with dozens of columns, all of which were shifted by one column to the right. I run through the API but I couldn't find a method to rotate the columns to the specific positions I was expecting, and my only options seemed to be either using set_axis, reindex or even slicing [[col1, col2, ..]] as a last chain. TBH, manually writing dozens of columns would not have been a good idea! While that day I was only concerned with rotating the columns, I later found myself in situations where I also needed to rotate the index. This led me to open this issue and suggest adding a rotate method to ./pandas/core/frame.py in the future, but I wonder if it's possible and/or worthwhile.

Feature Description

The rotate would look like something like this :

import pandas as pd
import numpy as np

#for reproducibility
class TwinDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def rotate(self, wheels: int, clockwise: bool = True, axis: int = 1) -> pd.DataFrame:
        if axis == 1:
            len_axis = len(self.columns)
            axis_names = self.columns
        elif axis == 0:
            len_axis = len(self)
            axis_names = self.index
        if wheels % len_axis == 0:
            return self
        shift = wheels % len_axis if clockwise else -wheels % len_axis
        result = self.reindex(axis_names[np.roll(np.arange(len_axis), shift)], axis=axis)
        return result

Test & Output :

df = TwinDataFrame({"A": [1, 2, 3, 4],
              "B": [5, 6, 7, 8],
              "C": [9, 10, 11, 12]})

print(df)
   A  B   C
0  1  5   9
1  2  6  10
2  3  7  11
3  4  8  12

rot_df = df.rotate(wheels=2, clockwise=False, axis=1)

print(rot_df)
    C  A  B
0   9  1  5
1  10  2  6
2  11  3  7
3  12  4  8

Additional Context

No response

Comment From: MarcoGorelli

thanks @abokey1 for the suggestion

your function looks fine

I wouldn't add it to the pandas API though

Comment From: abokey1

I wouldn't add it to the pandas API though

Hi @MarcoGorelli, can you elaborate, please ? That's why I haven't created a PR btw ;)

Comment From: MarcoGorelli

it just doesn't look widely useful enough, and the API is already gigantic

Comment From: mroeschke

Thanks for the suggestion but I would also be -1 to include this in the already large API. I think a user using your function in their local implementation should be sufficient and doesn't warrant maintenance on the pandas side. Closing

Comment From: abokey1

@MarcoGorelli, @mroeschke, Thank you guys for the feedback ;)