moham
moham

Reputation: 41

filter pandas dataframe on column and add string to the filtered data

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']'])

Upvotes: 1

Views: 284

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61900

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.

Upvotes: 3

Related Questions