Home > other >  Moving Pandas Dataframe Columns to the start
Moving Pandas Dataframe Columns to the start

Time:12-27

I've got a pandas dataframe with almost a thousand columnds

The column titles are like

[smth,smth,smth,smth.....a,b,c,d,e]

how would I re arrange the columns to move A,B,C,D,E to the start:

[a,b,c,d,e,smth,smth......]

CodePudding user response:

If I were you I would just use the included .pop() method that is built in to pandas.

So in your case I would do something like this: You will end up with a dataFrame where the column the pop method was used on is now the first and it will subsequently shift all the rest.

first_column = df.pop('A')

You could continue to do this for each of the other columns and it would work well, and if you have so much data that it becomes cumbersome to do it this way you could just run a loop.

There is also some good info from pandas on this:

https://www.geeksforgeeks.org/how-to-move-a-column-to-first-position-in-pandas-dataframe/

CodePudding user response:

A clean and efficient way is to use reindex:

cols = list(df.columns)
df.reindex(columns=cols[-5:] cols[:-5])

Example:

df = pd.DataFrame([], columns=['X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E'])
print(df)

cols = list(df.columns)
df = df.reindex(columns=cols[-5:] cols[:-5])
print(df)

output:

Empty DataFrame
Columns: [X, Y, Z, A, B, C, D, E]
Index: []

Empty DataFrame
Columns: [A, B, C, D, E, X, Y, Z]
Index: []
  • Related