0

I'm trying to generate a dataframe using Pandas like this:

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()

the problem is that I'm getting this order of columns: "y | x | z | Area"

How can I get this ordering "x | y | z | Area" as specified in the variable "my_dic" ? I tried the attribute df.columns=['x','y','z','Area'] but in vain. (I'm using python 2.7)

yankee
  • 123
  • 1
  • 1
  • 8

1 Answers1

1

Consider several ways to specify column ordering:

# 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')

Aside - dictionary construction from dict() is usually slower than defining keys and values inside {} as this answer shows. And pandas.DataFrame constructor can directly receive many data structures (dict, list, tuple, set, pandas.Series, numpy.array) as first argument.

Parfait
  • 104,375
  • 17
  • 94
  • 125
  • Thank you for your responses. Your first response isn't good for my case because I have arrays of different lengths. I'm getting this error: "arrays must all be same length". 2) your second response makes this error: "['x' 'y' 'z' 'Area'] not in index". I didn't understand why. 3) Your third response is good if I omit axis='columns'. – yankee Jul 24 '18 at 09:33
  • Those are strange errors for 2 and 3. It sounds like, *x*, *y*, *z*, and *Area* those are not columns. Possibly your output is rendering hierarchical or multindexes levels. Hard to tell without a [reproducible example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – Parfait Jul 24 '18 at 13:42