简体   繁体   中英

Column Order in Pandas Dataframe from dict of dict

I am creating a pandas dataframe from a dictionary of dict in the following way :

df = pd.DataFrame.from_dict(stats).transpose()

I want the columns in a particular order but cant seem to figure out how to do so. I have tried this:

df = pd.DataFrame(columns=['c1','c2','c3']).from_dict(stats).transpose() 

but the final output is always c3, c2, c1 . Any ideas ?

You could do:

df = pd.DataFrame.from_dict(stats).transpose().loc[:, ['c1','c2','c3']]

or just

df = pd.DataFrame.from_dict(stats).transpose()[['c1','c2','c3']]

If you know the order, you can manually adjust as follows:

df = df[['c1','c3','c2']]

You can also do it by just creating a list of column names

disiredOrder = ['c1','c3','c2']
df = df[disiredOrder]

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