在多个数据帧中使用重命名功能遍历大熊猫数据帧的字典以重命名列

问题描述

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

``a_dict = {'布里斯托尔':'25005','普利茅斯':'25023','伍斯特':'25027','希尔斯伯勒':'33011','罗金厄姆':'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'    

解决方法

不是通过字符串名称recommended创建DataFrames,更好的是创建DataFrames的字典(并重命名):

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()})