0

I want to align the keys in pandas to the columns they belong to. I have the code, and the output below, with an example of what I am trying to do.

Code:

df = pd.read_csv('Filename.txt')
df.columns = ['Date','b1','b2','b3']
df = df.set_index('Date')

reversed_df = df.iloc[::-1]

n=5
print('Game')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(reversed_df.drop(df.index[n:-n]),("\n"))

BallOne = pd.get_dummies(reversed_df.b1)
BallTwo = pd.get_dummies(reversed_df.b2)
BallThree = pd.get_dummies(reversed_df.b3)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', None)
print(pd.concat([BallOne, BallTwo, BallThree], keys = ['D3E-B1', 'D3E-B2', 'D3E-B3'], axis=1),("\n"))

Output:

           D3E-B1                            D3E-B2                            D3E-B3                           
                0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9
Date                                                                                                            
1984-09-01      0  0  0  0  0  0  0  0  0  1      0  0  0  0  1  0  0  0  0  0      0  0  0  0  0  0  0  0  1  0
1984-09-03      0  1  0  0  0  0  0  0  0  0      0  0  0  0  0  1  0  0  0  0      0  0  0  1  0  0  0  0  0  0

I would like the keys to be centered on their column like this:

                D3E-B1                            D3E-B2                            D3E-B3                           
                0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9
Date                                                                                                            
1984-09-01      0  0  0  0  0  0  0  0  0  1      0  0  0  0  1  0  0  0  0  0      0  0  0  0  0  0  0  0  1  0
1984-09-03      0  1  0  0  0  0  0  0  0  0      0  0  0  0  0  1  0  0  0  0      0  0  0  1  0  0  0  0  0  0

1 Answers1

1
from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

from: Pretty Printing a pandas dataframe

Sharpie
  • 41
  • 1