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 series pad function not working with apply in pandas

I am trying to write the code to pad columns of my pandas dataframe with different characters. I tried to use apply function to fill ‘0’ with zfill and it works.

print(df["Date"].apply(lambda x: x.zfill(10)))
   

But when I try to use pad function using apply method to my dataframe I face error:
AttributeError: ‘str’ object has no attribute ‘pad’

The code I am trying is:

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

 print(df["Date"].apply(lambda x: x.pad(10, side="left", fillchar="0")))

Both the zfill and pad functions are a part of pandas.Series.str. I am confused why pad is not working and zfill works. How can I achieve this functionality?

Full code:

import pandas as pd
from io import StringIO

StringData = StringIO(
    """Date,Time
パンダ,パンダ
パンダサンDA12-3,パンダーサンDA12-3
パンダサンDA12-3,パンダサンDA12-3
    """
)

df = pd.read_csv(StringData, sep=",")

print(df["Date"].apply(lambda x: x.zfill(10))) -- works
print(df["Date"].apply(lambda x: x.pad(10, side="left", fillchar="0"))) -- doesn't work

I am using pandas 1.5.1.

>Solution :

You should just not use apply, doing so you don’t benefit from Series methods, but rather use pure python str methods:

print(df["Date"].str.zfill(10))
print(df["Date"].str.pad(10, side="left", fillchar="0"))

output:

0       0000000パンダ
1      パンダサンDA12-3
2    パンダサンDA12-3
Name: Date, dtype: object
0       0000000パンダ
1      パンダサンDA12-3
2    パンダサンDA12-3
Name: Date, dtype: object

multiple columns:

Now, you need to use apply, but this is DataFrame.apply, not Series.apply:

df[['col1', 'col2', 'col3']].apply(lambda s: s.str.pad(10, side="left", fillchar="0"))
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