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
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']})
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')
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 rowsstr('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
Choosing a File in Python with Simple Dialog
Python 3: Importerror "No Module Named Setuptools"
Running Selenium with Headless Chrome Webdriver
Python: JSON.Loads Returns Items Prefixing with 'U'
Python Process Pool Non-Daemonic
How to Print to Stderr in Python
Traverse a List in Reverse Order in Python
Function for Factorial in Python
Why Are Empty Strings Returned in Split() Results
Why Is Parenthesis in Print Voluntary in Python 2.7
Why Do I Need 'B' to Encode a String with Base64
Differencebetween Drawing Plots Using Plot, Axes or Figure in Matplotlib
Remove Punctuation from Unicode Formatted Strings
Python/Numpy First Occurrence of Subarray
Is Distributing Python Source Code in Docker Secure
Python - Extracting and Saving Video Frames
What Does 'Valueerror: Cannot Reindex from a Duplicate Axis' Mean