Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pandas sort columns by name

df = df.reindex(sorted(df.columns), axis=1)
Comment

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 :: how to disable resizing in tkinter 
Python :: merge two df 
Python :: python code to remove file extension 
Python :: comparing two dataframe columns 
Python :: string startswith python 
Python :: palindrome rearranging python 
Python :: double for in python 
Python :: python for loop in one line 
Python :: get title attribute beautiful soup 
Python :: stdout.write python 
Python :: add text to pygame window 
Python :: How to return images in flask response? 
Python :: tkinter open new window 
Python :: finding the index of an item in a pandas df 
Python :: how to restart program in python 
Python :: find by class bs4 
Python :: linear congruential generator in python 
Python :: channel lock command in discord.py 
Python :: sum of column in 2d array python 
Python :: Math Module sqrt() Function in python 
Python :: python file handling 
Python :: python ftp login 
Python :: frequency spectrum signal python 
Python :: python cv2 get image shape 
Python :: Simple way to measure cell execution time in jupyter notebook 
Python :: create bigram in python 
Python :: docx change font python 
Python :: how to make a sigmoid function in python 
Python :: second y axis matplotlib 
Python :: python frame in a frame 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =