简体   繁体   中英

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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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