user531525
user531525

Reputation: 87

Iterating through a dictionary of pandas dataframes to rename columns using the rename function in multiple dataframes

a_dict = {'Bristol': '25005','Plymouth': '25023','Worcester': '25027','Hillsborough' :'33011', 'Rockingham':'33015'}

`` a_dict = {'Bristol': '25005','Plymouth': '25023','Worcester': '25027','Hillsborough' :'33011', 'Rockingham':'33015'} n_dict = {'Br': dataBristol,'Pl' : dataPlymouth,'W': dataWorcester,'Hillsborough' :'H', 'Rockingham':'R'}

for key, value in a_dict.items():
    county = 'data'+str(key)
    county =  data[data["fips"] == str(value)]


for key1, value1 in n_dict.items():
    county1 = value1
    county1.rename(columns={'cases':"case"+str(key1), 'deaths': "deaths"+str(key1), 'population': 'pop'+str(key1)}, inplace = True)

AttributeError: 'str' object has no attribute 'rename'    

Upvotes: 1

Views: 72

Answers (1)

jezrael
jezrael

Reputation: 862851

It is not recommended create DataFrames by strings names, better is create dictonary of DataFrames (and also rename):

d = ({key: data[data["fips"] == str(value)].rename(columns={'cases':"case"+str(key), 
                                                           'deaths': "deaths"+str(key), 
                                                           'population': 'pop'+str(key)}) 
                 for key, value in a_dict.items()})

Upvotes: 1

Related Questions