-1

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.

  • So you just want to change how the df looks when you print it? Why? – timgeb Mar 07 '22 at 09:59
  • I am writing PDB file "Protein Data Bank" – Elsaid Sami Elsaid Mohamed Mar 07 '22 at 10:33
  • @ElsaidSamiElsaidMohamed then you might want to read [this](https://stackoverflow.com/questions/16490261/python-pandas-write-dataframe-to-fixed-width-file-to-fwf) or [`biopandas.pdb`](https://rasbt.github.io/biopandas/api_subpackages/biopandas.pdb/) – mozway Mar 07 '22 at 10:40

2 Answers2

1

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
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Which will thwart any attempts to apply algorithms to the df that expect numbers. OP's request is probably misguided. – timgeb Mar 07 '22 at 10:05
  • @timgeb I agree the request is weird (that's why I requested details on the ultimate goal), that said, just for display this seems a reasonable hack, no? – mozway Mar 07 '22 at 10:06
  • sure. But why not [monkeypatch](https://stackoverflow.com/questions/65456318/how-to-monkeypatch-dunder-methods-to-existing-instances) `__str__`/`__repr__` while you're at it? :D – timgeb Mar 07 '22 at 10:09
  • 1
    @timgeb Love it ;) – mozway Mar 07 '22 at 10:11
  • @mozway Thanks a lot! Can you explain a bit more, I need also to make space between two specific columns – Elsaid Sami Elsaid Mohamed Mar 07 '22 at 10:30
  • 1
    Couldn't resist – timgeb Mar 07 '22 at 10:36
  • @Elsaid now that you clarified your need, you should use a specific solution like `biopandas`, or write a custom function to format the output. Can you give a reproducible example? – mozway Mar 07 '22 at 10:41
1

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
timgeb
  • 76,762
  • 20
  • 123
  • 145