code below, I have multiple dataframes with the same structure and would like to change the column names.

import pandas as pd

data_1 = [[1, 'tom', 10], [2, 'nick', 15], [3, 'juli', 14]] 
data_2 = [[1, 'tom', 10], [2, 'nick', 15], [3, 'juli', 14]]  
data_3 = [[1, 'tom', 10], [2, 'nick', 15], [3, 'juli', 14]]  

df_1 = pd.DataFrame(data_1, columns = ['number', 'Name', 'Age']) 
df_2 = pd.DataFrame(data_2, columns = ['number', 'Name', 'Age']) 
df_3 = pd.DataFrame(data_3, columns = ['number', 'Name', 'Age']) 

df_1 = df_1.set_index('number', inplace = True)
df_2 = df_2.set_index('number', inplace = True)
df_3 = df_3.set_index('number', inplace = True)

df_list = [df_1, df_2, df_3]

for df in df_list :
    df = df.columns['New_name', 'New_Age']

This code returns :

AttributeError: 'list' object has no attribute 'columns'

when I'm using my real data

or

AttributeError: 'NoneType' object has no attribute 'columns'

with the MWE above.

thanks

1 Answers

1
michael petronav On Best Solutions

In stead of these :

df_1 = df_1.set_index('number', inplace = True)
df_2 = df_2.set_index('number', inplace = True)
df_3 = df_3.set_index('number', inplace = True)

Only do this :

df_1.set_index('number', inplace = True)
df_2.set_index('number', inplace = True)
df_3.set_index('number', inplace = True)

.set_index() is inplace method and returns None but modified the object in place.

Also, inside the for loop, instead of this

df = df.columns['New_name', 'New_Age']

Do this :

df.columns = ['New_name', 'New_Age']