Add a String Prefix to Each Value in a String Column Using Pandas

add a string prefix to each value in a string column using Pandas

df['col'] = 'str' + df['col'].astype(str)

Example:

>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0

add suffix based on multiple conditions from string values in another column

You need to proceed in 3 steps

  1. You need to define an exhaustive suffix_list - a dictionary that holds information only once for each market

    suffix_list = pd.DataFrame({'Market': ['Oslo', 'Paris'], 'suffix':['OL','PA']})

  2. You want to merge the suffix_list into your existing dataframe as a new column - one command for all markets (for each market that has a suffix in the list, you add that suffix):

    pd.merge(df, suffix_list, how='left', on='Market')

  3. Now that you have the 2 columns 'value' and 'suffix' next to each other for all rows, you can apply 1 single operation for all rows

    str('value')+'suffix'

How to add a prefix to a string if it ends with a particular character (Pandas) i.e. add '-' to string given it ends with '-'

def add_prefix(text):
# If text is null or empty string the -1 index will result in IndexError
if text and text[-1] == "-":
return "-"+text
return text

df = pd.DataFrame(data={'A':["MAY500", "MAY500-", "", None, np.nan]})
# Change the column to string dtype first
df['A'] = df['A'].astype(str)
df['A'] = df['A'].apply(add_prefix)

0 MAY500
1 -MAY500-
2
3 None
4 nan
Name: A, dtype: object

How to add a suffix (or prefix) to each column name?

You can use a list comprehension:

df.columns = [str(col) + '_x' for col in df.columns]

There are also built-in methods like .add_suffix() and .add_prefix() as mentioned in another answer.

Pandas, adding prefix to values if the original value is less than 3 characters

Do you mean zfill:

df = pd.DataFrame({'ctx':['0','.x','001', 'abcd']})
df['ctx'].str.zfill(4)

Output:

0    0000
1 00.x
2 0001
3 abcd
Name: ctx, dtype: object

Add new column to pandas data frame based on string + value from another column in the data frame

Use:

df['axis'] = 'up to ' + df['end'].astype(str)


Related Topics



Leave a reply



Submit