0

This question shows how one might print multi-line strings with indents, but it doesn't work for pandas outputs.

Take the following example:

d = pd.DataFrame(dict(x = list(range(10)), y = list(range(10))))
print(f"\t{d}")

yields:

       x  y
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5
6  6  6
7  7  7
8  8  8
9  9  9

I want it to indent the whole table, not just the first two lines. Is there an easy way to do this without complicated parsing?

generic_user
  • 3,430
  • 3
  • 32
  • 56

2 Answers2

1

You could do:

>>> print('\t' + str(d).replace('\n', '\n\t'))
       x  y
    0  0  0
    1  1  1
    2  2  2
    3  3  3
    4  4  4
    5  5  5
    6  6  6
    7  7  7
    8  8  8
    9  9  9

Now there is probably a prettier way to do it but this one is pretty simple and ready to understand (replace new line by new line + tab)

EDIT A little less "hacky", where you can handle every lines the same way:

print('\n'.join(f'\t{line}' for line in str(d).split('\n')))

Works by splitting every line into a value, modifying that value and then joining them again into a single string

Mengard
  • 222
  • 1
  • 8
0

Looks like there is a .to_string(), method. Do that then use the method in the linked question:

import textwrap
def indent(text, amount, ch=' '):
        return textwrap.indent(text, amount * ch)
d = pd.DataFrame(dict(x = list(range(10)), y = list(range(10)))).to_string()
print(f"{indent(d, 4)}")
generic_user
  • 3,430
  • 3
  • 32
  • 56