I'm trying to print the columns of a data frame in an easy to read way. Currently my code looks like this:
In [ ]:
import pandas as pd
def printmastercolumns():
columncount = 0
for col in masterdf.columns:
columncount += 1
#prints each column with a number and a divider '|'
print(columncount," ",col ,end =" | ")
masterdf = pd.read_csv(r'C:\master.csv')
printmastercolumns()
Out [ ]:
1 Customer | 2 Name | 3 Address1 | 4 Address2 | 5 City | 6 Zip/Postal | 7 State/Prov | 8 Mailing Address1 | 9 Mailing Address2 | 10 Mailing City | 11 Mailing State/Prov | 12 Mailing Zip/Postal | 13 Fax | 14 Toll Free | 15 SalesRep | 16 Comments | 17 CreditLimit | 18 Business Partner Info1 | 19 Info3 | 20 Info 5 |
But I would rather the output looks more like this:
Out [ ]:
1 Customer | 7 State/Prov | 13 Fax | 19 Info3 |
2 Name | 8 Mailing Address1 | 14 Toll Free | 20 Info 5 |
3 Address1 | 9 Mailing Address2 | 15 SalesRep |
4 Address2 | 10 Mailing City | 16 Comments |
5 City | 11 Mailing State/Prov | 17 CreditLimit |
6 Zip/Postal | 12 Mailing Zip/Postal | 18 Business Partner Info1 |
It doesn't have to be perfect. I'm just looking for a more organized way to display each column name with a number next to it.
Thank you!
UPDATE Answer:
In [ ]:
import pandas as pd
import cmd
def printmastercolumns():
columncount = 0
collist = []
for col in masterdf.columns:
# combine all column numbers and names as strings in a list
columncount += 1
countstr = str(columncount)
col = countstr + " " + col
ColList.append(col)
# print the column list in columns using cmd
cli = cmd.Cmd()
cli.columnize(ColList, displaywidth=80)
masterdf = pd.read_csv(r'C:\master.csv')
printmastercolumns()
Out [ ]:
1 Customer 6 Zip/Postal 11 Mailing State/Prov 16 Comments
2 Name 7 State/Prov 12 Mailing Zip/Postal 17 CreditLimit
3 Address1 8 Mailing Address1 13 Fax 18 Business Parter Info1
4 Address2 9 Mailing Address2 14 Toll Free 19 Info3
5 City 10 Mailing City 15 SalesRep 20 Info 5