Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pandas reorder columns

# setting up a dummy dataframe
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
        'age': [20, 19, 22, 21],
        'favorite_color': ['blue', 'red', 'yellow', "green"],
        'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data, index = ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'])
df

#now 'age' will appear at the end of our df
df = df[['favorite_color','grade','name','age']]
df.head()
Comment

pandas reorder columns by name

#old df columns
df.columns
Index(['A', 'B', 'C', 'D'],dtype='***')
#new column format that we want to rearange
new_col = ['D','C','B','A'] #list of column name in order that we want

df = df[new_col]
df.columns
Index(['D', 'C', 'B', 'A'],dtype='***')
#new column order
Comment

pandas reorder columns

# Get column list in ['item1','item2','item3'] format 
df.columns
# [0]output: 
Index(['item1','item2','item3'], dtype='object')

# Copy just the list portion of the output and rearrange the columns 
cols = ['item3','item1','item2']

# Resave dataframe using new column order
df = df[cols]
Comment

reorder columns pandas

cols = df.columns.tolist()
# Rearrange the list any way you want
cols = cols[-1:] + cols[:-1]
df = df[cols]
Comment

how to reorder columns in pandas

Reorder columns in pandas
Comment

PREVIOUS NEXT
Code Example
Python :: seaborn plot to see outliers 
Python :: pandas parameters read 
Python :: geopandas plot fullscreen 
Python :: pd assign index from different df 
Python :: nlargest of each group 
Python :: python generate sine wave pyaudio 
Python :: divide all the numbers of a list by one number python 
Python :: torch.tensor.expand 
Python :: concat with zero array numpy 
Python :: pandas 3d set camara cords 
Python :: check entries smaller 0 after groupby 
Python :: how to import the whall library in python 
Python :: import cv2 illegal instruction (core dumped) 
Python :: python boolean ungleich 
Python :: multiplication table for number python codewars 
Python :: python numpy 
Python :: python open application windows 
Python :: how to make a chrome extension in python 
Python :: select specific columns in sqlalchemy 
Python :: how to add a key in python dictionary 
Python :: python function to multiply two numbers 
Python :: index in for loop 
Python :: bounding box in python 
Python :: divide list into equal parts python 
Python :: python get an online file 
Python :: python round function example 
Python :: df read csv 
Python :: setdefault python 
Python :: tuple unpacking 
Python :: shape function python 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =