Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to change the column order in pandas dataframe

df = df.reindex(columns=column_names)
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

# 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

pandas change column order

df[['column2', 'column3', 'column1']]
Comment

reorder columns pandas

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

rearrange columns pandas

You could also do something like this:

df = df[['mean', '0', '1', '2', '3']]
You can get the list of columns with:

cols = list(df.columns.values)
The output will produce:

['0', '1', '2', '3', 'mean']
Comment

how to reorder columns in pandas

Reorder columns in pandas
Comment

pandas change column order

frame = frame[['column I want first', 'column I want second'...etc.]]
Comment

PREVIOUS NEXT
Code Example
Python :: #adding new str to set in python 
Python :: lucky number codechef solution 
Python :: Remove whitespace from str 
Python :: python program to check whether a number is even or odd 
Python :: python common elements in two arrays 
Python :: nltk 
Python :: pandas dataframe caption 
Python :: check if 2 strings are equal python 
Python :: len of iterator python 
Python :: array creation in numpy 
Python :: check null all column pyspark 
Python :: class inside class python 
Python :: python no label in legend matplot 
Python :: python get attribute value with name 
Python :: SUMOFPROD1 Solution 
Python :: regex find all french phone number python 
Python :: df length 
Python :: opencv webcam 
Python :: Change one value based on another value in pandas 
Python :: Append a line to a text file using the write() function 
Python :: django loginview 
Python :: join in pathlib path 
Python :: numpy round to nearest 5 
Python :: add favicon in django admin 
Python :: counter library python 
Python :: current page django 
Python :: tkinter python button 
Python :: Subset data frame by date 
Python :: text to image python 
Python :: how to import matplotlib in python 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =