Home > Back-end >  Pandas series pad function not working with apply in pandas
Pandas series pad function not working with apply in pandas

Time:10-25

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:

 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.

CodePudding user response:

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"))
  • Related