Skip to content
Advertisement

rename a dataframe automatically

I want to automatically rename my dataframe with 3 name ,I tried with this code but it shows me each time only the last name :

nombres=['x','y','z']
for j in range(len(nombres)):
df.columns=[ nombres[j] +str(i) for i in range(1, len(df.columns) + 1)]

the result I want to achieve :

    x   y   z   x   y   z   x   y   z   
    0   0   7   18  90  1   80  15  3

Advertisement

Answer

Can do it dynamically by multiplying the list to repeat it. Then slice by the length of the df.columns

import pandas as pd
import math

df = pd.DataFrame([[0,0,7,18,90,1,80,15,3]])
nombres=['x','y','z']


nombres = nombres * math.ceil((len(df.columns)/len(nombres)))
df.columns = nombres[:len(df.columns)] 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement