Tuesday, July 20, 2021

Reversing the order (rows and columns) of dataframe in R and Python

 Lets see how to reverse the order of dataframe rows and columns in both R and Python scripting.


Reversing the order of rows and columns in Python

import pandas as pd

# Define the DataFrame...
df = pd.DataFrame({'Col1':['Africa', 'Asia', 'Europe', 'North America', 'South America'], 
                     'Col2':[1000, 3000, 6000, 9000, 12000]})

df


# Reversing the order of ROWS
df[::-1].reset_index(drop=True)

# Or

df.iloc[::-1]


# Reversing the order of COLUMNS
df[df.columns[::-1]]

# Or

df.iloc[:, ::-1]



Reversing the order of  rows and columns in R

# Define the DataFrame...
df <- data.frame('Col1'=c('Africa', 'Asia', 'Europe', 'North America', 'South America'),
                'Col2'=c(1000, 3000, 6000, 9000, 12000))


# Reversing the order of ROWS
rev_dfr <- apply(df, 2, rev)

# Reversing the order of COLUMNS
rev_dfc <- rev(df)


That is it!

No comments:

Post a Comment