Reorder a dataframe from a dictionary with columns of different size using python
本问题已经有最佳答案,请猛点这里访问。
我正在尝试使用像这样的Pandas生成数据帧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pandas as pd x='x' y='y' z='z' Area='Area' #len(coords_x)==len(coords_y)==len(coords_z)==64 #len(area[:,0])==18 my_dict = dict( x= np.asarray(coords_x),y= np.asarray(coords_y), z= np.asarray(coords_z), Area= area[:,0]) df = pd.DataFrame.from_dict(my_dict, orient='index') df=df.transpose() writer = ExcelWriter('my_data.xlsx') df.to_excel(writer,'Sheet1',index=False) writer.save() |
问题是我得到了这个列的顺序:"y | x | z | Area"
如何在变量"my_dic"中指定的"x | y | z | Area"排序? 我尝试了属性df.columns = ['x','y','z','Area']但是徒劳无功。 (我正在使用python 2.7)
考虑几种指定列排序的方法:
1 2 3 4 5 6 7 8 | # COLUMNS ARGUMENT OF DATAFRAME CONSTRUCTOR df = pd.DataFrame(my_dict, columns=['x','y','z','Area']) # SPECIFYING COLUMNS AFTER DATAFRAME BUILD df = pd.DataFrame.from_dict(my_dict, orient='index')[['x','y','z','Area']] # REINDEXING df = pd.DataFrame.from_dict(my_dict, orient='index').reindex(['x','y','z','Area'], axis='columns') |
旁白 -