简体   繁体   English

通过字典键合并数据框重命名列的Python

[英]Python on merging dataframe rename columns by dictionaries keys

Initially, I have an empty dataframe with date field and later I am trying to merge it with the new dataframe in a for loop. 最初,我有一个带日期字段的空数据框,后来我尝试将其与for循环中的新数据框合并。

com_df = pd.DataFrame(columns=['date'])
    for i in data_dict.values():
        response = requests.get('www.example.com/' + i + '?format=json')
        data = json.loads(response.content.decode('utf-8'))
        df = dataframe_format(data[1]) // convert list of dict to dataframe
        com_df = pd.merge(com_df, df, on='date', how='outer')

So the output for now is like, 所以现在的输出就像

    date       value_x       value_y  value_x     value_y       value
0   2017  1.722333e+13  8.711267e+12   3485.0  197.713256   46.030025
1   2016  1.829506e+13  7.320738e+12   3052.0  249.907289   -2.024998
2   2015  3.932602e+13  8.188019e+12   2827.0  480.287296   -6.007182

But I want the column name to be the keys of below dictionary, 但我希望列名成为以下字典的键,

data_dict = {'A': '1','B': '2','C': '3','D': '4','E': '5'}

that is, 那是,

    date           A              B        C            D       E 
0   2017  1.722333e+13  8.711267e+12   3485.0  197.713256   46.030025
1   2016  1.829506e+13  7.320738e+12   3052.0  249.907289   -2.024998
2   2015  3.932602e+13  8.188019e+12   2827.0  480.287296   -6.007182

If your intention is to apply the dictionary keys sorted by their values, then you can do this: 如果您打算应用按其值排序的字典键,则可以执行以下操作:

df.columns = [df.columns[0]] \
           + [k for k,_ in sorted(data_dict.items(), key=lambda x:x[1])]

I would transform your input dictionary to one mapping index to column name: 我会将您的输入字典转换为一个到列名的映射索引:

data_dict = {'A': '1','B': '2','C': '3','D': '4','E': '5'}
pos_col_dict = {int(v): k for k, v in data_dict.items()}

Then assign to columns via NumPy. 然后通过NumPy分配给列。 You should use a copy to avoid side-effects: 您应该使用副本以避免副作用:

arr = df.columns.values
arr[list(pos_col_dict)] = list(pos_col_dict.values())
df.columns = arr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM