Home > Net >  Shifting a certain column to far rigth in pandas "without changing the columnvalues"
Shifting a certain column to far rigth in pandas "without changing the columnvalues"

Time:03-08

I want to shift a column['d'] to far-right

   a  b  c   d
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12

The desired df Looks like this:

   a  b  c       d
0  1  4  7      10
1  2  5  8      11
2  3  6  9      12

A custom df:

         A   B    C    D  E  F       G      H      I  J
0   HETATM   1   CM  MEG  A  1 -14.139  2.599  0.003  C
1   HETATM   2  HM1  MEG  A  1 -14.184  3.047 -1.015  H
2   HETATM   3  HM2  MEG  A  1 -15.130  2.652  0.503  H
3   HETATM   4  HM3  MEG  A  1 -13.868  1.531 -0.121  H
4   HETATM   5   OM  MEG  A  1 -13.151  3.216  0.791  O

I want to have two spaces between 'B' and 'C'. I want to shift a column 'J' to far right.

CodePudding user response:

This is a bit weird request, you should give more details on what you really want to achieve.

You could insert a blank column with:

df.insert(df.shape[1]-1, ' ', '')

output:

   a  b  c     d
0  1  4  7    10
1  2  5  8    11
2  3  6  9    12

CodePudding user response:

Just do this. I promise it's good code.

class Shift(pd.DataFrame):
    def __repr__(self):
        _df = self[:]
        _df.insert(self.shape[1]-1, ' ', '')
        return repr(_df)

df.__class__ = Shift

Demo:

>>> df
   a  b  c   d
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12
>>> df.__class__ = Shift
>>> df
   a  b  c     d
0  1  4  7    10
1  2  5  8    11
2  3  6  9    12
  • Related