【问题标题】:Iterating through a dictionary of pandas dataframes to rename columns using the rename function in multiple dataframes在多个数据帧中使用 rename 函数遍历 pandas 数据帧字典以重命名列
【发布时间】:2020-12-21 07:44:07
【问题描述】:
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'    

【问题讨论】:

    标签: python pandas dataframe dictionary rename


    【解决方案1】:

    这不是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()})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多