kaban
kaban

Reputation: 433

How to pretty format columns, values in pandas so they stand same width?

for x in basic_data.columns:
    print( type(basic_data[x][4000]) , "\t\t\t\t\t", basic_data[x][4000])

and when I print it, it looks uneven, i want both columns, type & value be same width apart from each other.

<class 'str'>                            ФАО ЦЕСНАБАНК г. Степногорск
<class 'str'>                            ежемесячно
<class 'str'>                            Стандартный
<class 'pandas._libs.tslibs.timestamps.Timestamp'>                           2015-06-01 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>                           2015-05-06 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>                           2017-05-06 00:00:00
<class 'numpy.float64'>                              220000.0
<class 'numpy.int64'>                            25
<class 'numpy.float64'>                              37.5
<class 'numpy.int64'>                            0
<class 'str'>                            Акмолинская Область
<class 'str'>                            Собственное
<class 'str'>                            Казахстан
<class 'str'>                            Потребительские цели
<class 'pandas._libs.tslibs.timestamps.Timestamp'>                           2015-05-06 00:00:00
<class 'numpy.int64'>                            24
<class 'numpy.float64'>                              6.0
<class 'pandas._libs.tslibs.timestamps.Timestamp'>                           2015-05-04 00:00:00
<class 'numpy.float64'>                              1.0
<class 'str'>                            Взнос наличными деньгами
<class 'str'>                            От 1 года  до 5 лет
<class 'numpy.float64'>                              1.0
<class 'numpy.float64'>                              33862.11

Upvotes: 0

Views: 34

Answers (1)

rpanai
rpanai

Reputation: 13447

Maybe there is a better way but you can notice that the max length for type is 50. Let's make an example

import pandas as pd
n = 4001
df = pd.DataFrame({"a":["wcewcvevc"] * n ,
                   "b":["2019-01-01"] * n,
                   "c":[1.01] * n,
                   "d":[25] * n})
df["b"] = df["b"].astype("M8[us]")
out = []
for col in df.columns:
    out.append([len(str(type(df[col].iloc[4000]))),len(str(df[col].iloc[4000]))])
pd.DataFrame(out).max().tolist()
# output [50, 19]

# then you can define a layout as
lyt = "{:<55}{:24}"

# and print
for col in df.columns:
    print(lyt.format(str(type(df[col].iloc[4000])), str(df[col].iloc[4000])))

and the output is

<class 'str'>                                          wcewcvevc               
<class 'pandas._libs.tslibs.timestamps.Timestamp'>     2019-01-01 00:00:00     
<class 'numpy.float64'>                                1.01                    
<class 'numpy.int64'>                                  25     

Upvotes: 2

Related Questions