I am trying to add a suffix to a few columns of the pandas dataframe without touching the existing columns. I tried with the below code but it removes all the other columns:
df_client.iloc[:,-3:].add_suffix('_P1')
I can break the dataframe in two, rename columns of the 2nd dataframe and merge them back, but I wanted to know if there is an easier option available in pandas.
Sample input: df:
Name DL PL KH DL PL KH
A 1 1 2 3 4 1
B 1 1 2 3 4 1
Expected output: df:
Name DL PL KH DL_P1 PL_P1 KH_P1
A 1 1 2 3 4 1
B 1 1 2 3 4 1
CodePudding user response:
When you use df.columns
it outputs a collection of strings. These are the column names.
If you have a list of column names you want to change to, let's say it's called new_list
, you can do df.columns = new_list
. This changes the names of all the columns, without changing data. (Gotta make sure the lists are the same length)
So just prepare a list of new column names.
new_columns = list(df.columns[:-3]) [c "_P1" for c in df.columns[-3:]]
Then simply df.columns = new_columns
.
CodePudding user response:
No there isn't a builtin function, you can use a custom function:
def suffix():
yield ''
i = 0
while True:
i = 1
yield f'_P{i}'
from collections import defaultdict
d = defaultdict(suffix)
df.columns = df.columns.map(lambda x: x next(d[x]))
output:
Name DL PL KH DL_P1 PL_P1 KH_P1
0 A 1 1 2 3 4 1
1 B 1 1 2 3 4 1