Home > Software design >  Pandas rename selected columns with sequential numbers
Pandas rename selected columns with sequential numbers

Time:01-25

I have a df with a number or columns, I would like to rename these with incremental numbers selecting the starting and ending range.

enter image description here

With the above image, I would like to select only columns B-D, and rename them to 1-4. So the resulting data frame would be:

enter image description here

So basically selecting the headers via index numbers and adding incremental numbers instead.

EDIT: The above dataframe

data = [['a','b','c','d','e','f'], ['a','b','c','d','e','f'], ['a','b','c','d','e','f'],['a','b','c','d','e','f']]

df = pd.DataFrame(data, columns = ['A','B','C','D','E','F'])

CodePudding user response:

Use rename with selected columns by DataFrame.loc - here between B and E:

c = df.loc[:, 'B':'E'].columns
df = df.rename(columns=dict(zip(c, range(1, len(c)   1))))
print (df)
   A  1  2  3  4  F
0  a  b  c  d  e  f
1  a  b  c  d  e  f
2  a  b  c  d  e  f
3  a  b  c  d  e  f

CodePudding user response:

If this is something you have to do frequently, you can write a custom function for that:

def col_rename(df, start, stop, inplace=False):
    cols = list(df.loc[:, start:stop].columns)
    new_cols = df.columns.map(lambda x: {k:v for v,k in
                                         enumerate(cols, start=1)
                                        }.get(x, x))
    if inplace:
        df.columns = new_cols
    else:
        return new_cols

df.columns = col_rename(df, 'B', 'F')

# or
# col_rename(df, 'B', 'F', inplace=True)

output:

   A  1  2  3  4  F
0  0  1  2  3  4  5

used input:

df = pd.DataFrame([range(6)], columns=list('ABCDEF'))

#    A  B  C  D  E  F
# 0  0  1  2  3  4  5
  •  Tags:  
  • Related