1

I am having a dataframe column that contains either 4 or 6 char strings in length, I would like to add "00" string to the end of the strings having length of 4.

I am using this code but its giving me a syntax error.

df['col'] = np.where((df['col'].str.len() = 4, df['col'].astype(str) +'00' , df['col']'])
1
  • 1
    df['col'].str.len() == 4 (you forgot one = sign) Commented Dec 20, 2020 at 14:49

1 Answer 1

3

The clean pandas way to do this is to use ljust instead:

import pandas as pd

df = pd.DataFrame()
df['col'] = pd.Series(['aaaa', 'bbbbbb'], dtype='string')

df['col'] = df['col'].str.ljust(6, '0')
print(df)

Output

      col
0  aaaa00
1  bbbbbb

From the documentation above:

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

pandas offers a rich api to work with text, see this for more information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.