简体   繁体   中英

How to maintain the order in index when creating Pandas.Dataframe

I'm writing for help when creating the Dataframe.

The code is shown as follows:

import pandas as pd
import numpy as np
data = np.array([[1,2,3],[4,5,6],[2,6,3],[np.nan,np.nan,np.nan]])
index = {'M','B','C','D'}
columns = {'x','y','z'}
df_test = pd.DataFrame(data,index=index,columns=columns)
print('df_test is \n', df_test)

And the result is

     z    x    y
 B  1.0  2.0  3.0
 C  4.0  5.0  6.0
 M  2.0  6.0  3.0
 D  NaN  NaN  NaN

But I want to maintain the order in index and data, that is, I want to get the result as: (Please mind the order in index)

    z    x    y
M  1.0  2.0  3.0
B  4.0  5.0  6.0
C  2.0  6.0  3.0
D  NaN  NaN  NaN

Anyone who can help me? Thanks.

To keep the order you should use lists for index (instead of sets):

index = ['M','B','C','D']

If the columns' order also matters:

columns = ['x','y','z']

Use sort_index, as below:

df_test.sort_index(level=['M','B','C','D'])

You can also use directly the name of the list, instead of the entire list, which is helpful when it's many rows, like below:

df_test.sort_index(level=your_index)

where in this case is

your_index = ['M','B','C','D']

(avoid naming your_index as 'index' as you did in your question, because this name is already used from Python)

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