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

How to apply two transformations to a dataframe column

I’m wanting to change a dataframe column so the values are lower case and also have their whitespace stripped:

df.loc[:, column] = df.loc[:, column].str.lower().str.strip()

The above snippet works, but it looks quite messy as I have to use .str. twice – is there a better solution?

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

>Solution :

You can use a list comprehension:

df['col2'] = [x.lower().strip() for x in df['col']]

Doing this can be faster than chaining multiple str:

%%timeit
df['col2'] = df['col'].str.strip().str.lower()
# 344 ms ± 12.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
df['col2'] = [x.lower().strip() for x in s]
# 182 ms ± 3.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

used input (1M rows):

df = pd.DataFrame({'col': ['  aBc  DeF    ']*1000000})

NB. I used strip before lower in the comparison as this is faster than lower, then strip.

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