Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas dataframe to set all columns to be character length fixed

I have a csv file which column names are fixed width of 15. And its elements length different, depends on the data type.

Original

Name           ,Date           ,Time           ,TST Num        ,Dept/Dest      ,Tst Level      ,AAS            
AAAAAA         ,18/12/2007     ,07:57:40,AAA101         ,AAAABBBB       ,220,320
BBBBBB         ,18/12/2007     ,12:34:06,AAA112         ,XXXXYYYY       ,210,320

I will use Pandas to work on it. And the final output should look like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Final

Name           ,Date           ,Time           ,TST Num        ,Dept/Dest      ,Tst Level      ,AAS            
AAAAAA         ,18/12/2007     ,07:57:40       ,AAA101         ,AAAABBBB       ,220            ,320
BBBBBB         ,18/12/2007     ,12:34:06       ,AAA112         ,XXXXYYYY       ,210            ,320

I can convert each column like:

df = df.astype(str)
df['Time           '] = df['Time           '].apply('{:15s}'.format)

But I can’t do in this way:

all_columns = list(df)
df[all_columns] = df[all_columns].apply('{:15s}'.format)

Is there any way I can do it without a loop?

>Solution :

Have you tried applymap?
df.applymap(('{:15s}'.format)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading