1

I would like to export certain data contained in nested dictionaries to a PD dataframe and then to Excel:

counter=0
for m in [3]:
for column, wind_speed in enumerate(wind_speeds):
    for row,ti in enumerate(TIs): 
        if ~np.isnan(Mx_m_3[row,column]): 
            exec("dtb_dict.update({"+str(counter)+":{'case': '12', 
'WindSpeed': wind_speed, 'TI':ti, 
list_of_variables[0]:"+list_of_variables[0]+"[row,column], 
list_of_variables[1]:"+list_of_variables[1]+"[row,column]}})")
            counter+=1


a=pd.DataFrame.from_dict({i: dtb_dict[i]
                       for i in dtb_dict.keys() 
                       for j in dtb_dict[i].keys()},
                   orient='index')


writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')

I would like to have a dataframe with columns in order case, wind,speed, ti, list_of_variables[0], list_of_variables[1]

And I get: case, wind,speed, list_of_variables[1], list_of_variables[0], ti

Is there a way to specify order of nested dictionaries or rearrange the dataframe?

Thanks!

1 Answers1

0

You can easily do this for the pandas DataFrame.

Suppose we start with

a = pd.DataFrame({"case": list(range(10)), "wind,speed": list(range(10)), "list_of_variables[1]": list(range(10)), "list_of_variables[0]":list(range(10)), "ti": list(range(10))})

Then

a = a[["case", "wind,speed", "ti", "list_of_variables[0]", "list_of_variables[1]"]]

will sort your columns as you wish.

Jérôme Bau
  • 707
  • 5
  • 16