Change the names of multiple columns

Let's say I have a data frame with these column names:

['a','b','c','d','e','f','g'] 

And I would like to change the names from 'c' to 'f' (actually add a row to the column name), so the column names of all data columns look like this:

['a','b','var_c_equal','var_d_equal','var_e_equal','var_f_equal','g']

Ok, firstly, I created a function that changes the column names with the row I want:

df.rename(columns=lambda x: 'or_'+x+'_no', inplace=True)

But now I really want to understand how to implement something like this:

df.loc[:,'c':'f'].rename(columns=lambda x: 'var_'+x+'_equal', inplace=True)
+4
source share
2 answers

One way is to use a dictionary instead of an anonymous function. Both of the options below assume that the columns to be renamed are contiguous.

Adjacent Columns by Position

d = {k: 'var_'+k+'_equal' for k in df.columns[2:6]}
df = df.rename(columns=d)

Matched columns by name

If you need to calculate numeric indices:

cols = df.columns.get_loc
d = {k: 'var_'+k+'_equal' for k in df.columns[cols('c'):cols('f')+1]}
df = df.rename(columns=d)

Specific columns

:

d = {k: 'var_'+k+'_equal' for k in 'cdef'}
df = df.rename(columns=d)
+2

, :

:

new_columns = ['var_{}_equal'.format(c) if c in 'cdef' else c for c in columns]

:

import pandas as pd


df = pd.DataFrame({'a':(1,2), 'b':(1,2), 'c':(1,2), 'd':(1,2)})
print(df)
df.columns = ['var_{}_equal'.format(c) if c in 'cdef' else c
               for c in df.columns]
print(df)

:

   a  b  c  d
0  1  1  1  1
1  2  2  2  2

   a  b  var_c_equal  var_d_equal
0  1  1            1            1
1  2  2            2            2
+3

Source: https://habr.com/ru/post/1693489/


All Articles