Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend pandas dataframe entries to same length

If I have a dataframe that looks something like this:

from pandas import DataFrame as df

data_df = df(data={"Number": [234, 7892, 109736, 8384664088]})

print(data_df)

       Number
0         234
1        7892
2      109736
3  8384664088

How can I quickly extend the entries in the dataframe to be the length of the entry with the maximum length using a particular character? For example, if I use "#" to extend them to something like:

       Number
0  234#######
1  7892######
2  109736####
3  8384664088

like image 429
Kusi Avatar asked Jan 02 '23 00:01

Kusi


2 Answers

One way would be using str.ljust to fill the right side of the numbers cast to string with as many # as needed to reach the maximum length:

max_len = len(str(max(data_df.Number)))
data_df['Number'] = data_df.Number.astype(str).str.ljust(max_len, '#')

    Number
0  234#######
1  7892######
2  109736####
3  8384664088
like image 81
yatu Avatar answered Jan 03 '23 12:01

yatu


Find the max width with str.len and then use str.pad to pad each entry:

max_width = data_df['Number'].astype(str).str.len().max()
data_df['Number'].astype(str).str.pad(side='right', fillchar='#', width=max_width)
like image 38
Shaido Avatar answered Jan 03 '23 14:01

Shaido