Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Pandas dataframe according to list of column names [duplicate]

Tags:

python

pandas

I have a pandas dataframe like this-

d = {'class': [0, 1,1,0,1,0], 'A': [0,4,8,1,0,0],'B':[4,1,0,0,3,1],'Z':[0,9,3,1,4,7]}
df = pd.DataFrame(data=d)

    A   B   Z   class
0   0   4   0   0
1   4   1   9   1
2   8   0   3   1
3   1   0   1   0
4   0   3   4   1
5   0   1   7   0

and I have a list like this-['Z','B','class','A']

Now I want to sort my pandas dataframe according to the list of column names

therefore the new dataframe would have the columns names-

Z  B  class A
like image 673
ubuntu_noob Avatar asked Sep 01 '25 02:09

ubuntu_noob


1 Answers

Use reindex:

L = ['Z','B','class','A']
df = df.reindex(columns=L)

Or select by subset:

df = df[L]
like image 67
jezrael Avatar answered Sep 02 '25 16:09

jezrael