0 votes
1 view
in Python by (107k points)

I have the following DataFrame (df):

import numpy as np 

import pandas as pd 

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:

df['mean'] = df.mean(1)   

How can I move the column mean to the front, i.e. set it as the first column leaving the order of the other columns untouched?

1 Answer

0 votes
by (47.8k points)

The below-mentioned code will help you to get the desired result :

import numpy as np   

import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

cols = df.columns.tolist()

cols = cols[-1:] + cols[:-1]

df = df[cols] 

print(df)

image

 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...