How do I add a suffix to every value in one column in pandas

376 Views Asked by At

I keep trying to add a suffix to every single value in one column in a dataframe. I accidentally added what I wanted to be a suffix as a prefix. I don't know how to fix this. How do I change the prefix to a suffix in pandas?

3

There are 3 best solutions below

0
Michael Cao On

If your prefix is the same for every column and thus has a fixed length, you can trim that off using df[column].str[prefix_length:]. E.g. your prefix is '_asdf', so you want to trim off the first four characters from your column with df[column].str[4:].

To add a suffix, you can use df[column] = df[column] + suffix

2
Corralien On

You can use str accessor to transform prefix as suffix.

Suppose the following dataframe:

>>> df
           col1
0  _suffixHello
1  _suffixWorld

With str.replace:

df['col1'] = df['col1'].str.replace(r'(_suffix)(.*)', r'\2\1', regex=True)
print(df)

# Output
           col1
0  Hello_suffix
1  World_suffix

Or using str.slice:

suffix = '_suffix'
df['col1'] = df['col1'].str.slice(len(suffix)) + suffix
# same as
# df['col1'].str[len(suffix):] + suffix
print(df)

# Output
           col1
0  Hello_suffix
1  World_suffix
0
DapperMoose On

Let's first create a series to work with of 8 randomly chosen colors:

colors = np.array(['blue','brown', 'black', 'cyan', 'green', 'maroon', 'magenta', 'orange','pink', 'purple', 'red', 'teal','yellow' ])

s = pd.Series(np.random.choice(a = colors, size = 8, replace = False))

enter image description here

Assign a string that you'd like for your suffix to the variable, 'suffix':

Then use the apply method with a lambda function to concatenate your suffix to each element in the series. Make sure the dtypes of all your elements in your series/column are strings. If they're numbers, convert them to a str first, otherwise, you'll get an error because of mis-aligned dtypes.

enter image description here