Given pandas DataFrame, how can I add the suffix "_old" to all columns except two columns Id
and Name
?
import pandas as pd
data = [[1,'Alex',22,'single'],[2,'Bob',32,'married'],[3,'Clarke',23,'single']]
df = pd.DataFrame(data,columns=['Id','Name','Age','Status'])
To add a string after each column label of DataFrame in Pandas, call add_suffix() method on this DataFrame, and pass the suffix string as argument to add_suffix() method.
To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].
If you would like to add a prefix or suffix to multiple columns in a pyspark dataframe, you could use a for loop and . withColumnRenamed().
To add a string before each column label of DataFrame in Pandas, call add_prefix() method on this DataFrame, and pass the prefix string as argument to add_prefix() method.
You can use the rename method which gets a dictionary of {column -> new_name}
:
df = df.rename(columns={col: col+'_old'
for col in df.columns if col not in ['Id', 'Name']})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With