Skip to content

ENH: Why pandas does not offer (yet) the possibility of rotating a dataframe ? #52305

@abokey1

Description

@abokey1

Feature Type

  • 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closing CandidateMay be closeable, needs more eyeballsEnhancementNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions