KcFnMi
KcFnMi

Reputation: 6171

Print Pandas DataFrame using letters as column index (as in MS Excel) instead of numbers

I'm using Pandas to read a MS Excel .xlsx file, so far this is the code:

import pandas as pd

excel_file = 'test.xlsx'
df = pd.read_excel(excel_file, sheetname='Sheet2', header=None)
print(df)

And the output is:

   0  1  2
0  5  6  7
1  8  9  0
[Finished in 0.8s]

Instead, I would like to see it as in MS Excel:

   A  B  C
0  5  6  7
1  8  9  0
[Finished in 0.8s]

I mean column index should be letters. Is that possible?

Upvotes: 1

Views: 2429

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34086

Considering your dataframe to be this:

In [184]: df
Out[184]: 
   0  1  2
0  5  6  7
1  8  9  0

If you have a small number of columns, you can directly do this:

df.columns = ['A','B','C']

OR

If the number of columns is much more, do this:

You can use create a list with alphabets and assign it to df.columns:

In [189]: col_list = [ chr(i+65) for i in range(len(df.columns)) ]
In [190]: col_list
Out[190]: ['A', 'B', 'C']

In [191]: df.columns = col_list

In [192]: df
Out[192]: 
   A  B  C
0  5  6  7
1  8  9  0

Upvotes: 1

James
James

Reputation: 36691

If you only need up to Z, you can use:

df = df.rename(columns={i:chr(i+65) for i in range(26)})

Upvotes: 0

Related Questions