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: adding one space around value in string column

I swear this should be easy, but I can’t find the answer.

Example dataframe:

df = pd.DataFrame([['1', '3-3/4'], 
                   ['2', '1-1/2'],
                   ['3', '2'],
                   ['4', '5-1/4'],
                   ['5', '6']],
                  columns = ["ID", "Size"])

Example dataframe

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

All I want to do is to add one space before and after the value in the Size column. I’ve tried ljust, rjust, center, and pad, but they all fail to add because you have to account for the length of the string, which varies.

I want it to look something like this (pretend the x is a space):

Needed outcome

I’ve dug around online, but cannot find a way to resolve this. Would someone point me in the right direction?

Thanks!

>Solution :

IIUC, you just need

df['Size'] = ' ' + df['Size'] + ' '
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