Elegance of R in Python - Series: Post 2

Python's equivalent of R's rbind() function:

def rbind(df1, df2):
import pandas as pd
# Note this does not keep the original indexes of the df's and resets them to 0,1, 2, ...
return pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis = 1)

If you copy and run the above in python you can then use the cbind() function in python exactly as you would use it in R.

One of the amazing things about R is that it just works and has great simple functions that work as you would intuitively expect them to.

When you simply want to merge one data frame to the end of another column-wise, both of which have the same number of rows, i.e. concatenating two data frames column-wise – “column-binding” then R's cbind() function just works.

df3 = cbind(df1, df2) # and Voila!

The python equivalent using pandas is:

df3 = pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis = 1) # pas de voila.

So just define the cbind() function in python as above and you are good to go!

Bon voyage sans naufrage!

SHARE

Authors

  1. Faizan Khalid Mohsin says:

    Proficient in Python and R for supervised and unsupervised learning, predictive and prescriptive modeling, deep learning, time-series analysis, survival analysis, and longitudinal analysis, as well as building dashboards using Shiny.

  2. Saad Mohsin says:

    Great communication skills and extensive teaching experience in machine learning and statistics using R and Python.