Okiic.
Okiic.

Reputation: 117

How to apply borders when printing DataFrame in CLI?

I want to separate the DataFrame cells with something like │ and ─.

This is the code at the moment

game_board = [
    [" ", "X", " ", "X", " ", "X", " ", "X"],
    ["X", " ", "X", " ", "X", " ", "X", " "],
    [" ", "X", " ", "X", " ", "X", " ", "X"],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    ["O", " ", "O", " ", "O", " ", "O", " "],
    [" ", "O", " ", "O", " ", "O", " ", "O"],
    ["O", " ", "O", " ", "O", " ", "O", " "]
]
print DataFrame(game_board)

and this is the output:
enter image description here

How does one add borders to DataFrame inside CLI?

Upvotes: 1

Views: 1225

Answers (1)

cs95
cs95

Reputation: 402922

Use the tabulate package:

pip install tabulate

Call tabulate.tabulate with tablefmt='grid', to get neat squares around your frame elements.

import tabulate

df = pd.DataFrame(game_board)
print(tabulate.tabulate(df, tablefmt='grid', showindex=False))

+---+---+---+---+---+---+---+---+
|   | X |   | X |   | X |   | X |
+---+---+---+---+---+---+---+---+
| X |   | X |   | X |   | X |   |
+---+---+---+---+---+---+---+---+
|   | X |   | X |   | X |   | X |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
| O |   | O |   | O |   | O |   |
+---+---+---+---+---+---+---+---+
|   | O |   | O |   | O |   | O |
+---+---+---+---+---+---+---+---+
| O |   | O |   | O |   | O |   |
+---+---+---+---+---+---+---+---+

Upvotes: 6

Related Questions