Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add suffix to column names except some columns?

Tags:

python

pandas

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'])
like image 597
ScalaBoy Avatar asked Nov 19 '18 18:11

ScalaBoy


People also ask

How do I add a suffix to a specific column in Pandas?

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.

How do I include all columns except one in Pandas?

To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].

How do you add a suffix to all column names Pyspark?

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().

How do you add a prefix to a column name Pandas?

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.


1 Answers

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']})
like image 129
Max Segal Avatar answered Sep 17 '22 09:09

Max Segal