How to add a single row to a pandas dataframe

Spread the love

In this post, you will learn how to add a single row to a pandas dataframe using two method.

Method 1 – Using loc

Read a dataset to work with

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/Restaurant.csv"
df = pd.read_csv(url)
df = df.head()
df

Here, we have some data about restaurants. Now, to add a single row to this data, we will write

# add a row to the dataframe
df.loc[5] = [6, 'Good', 30]

Method 2 – append

To add one row to a dataframe, you can also use the DataFrame.append() method in pandas.

df = df.append({"Restaurant": 7, "Quality Rating": "Excellent", 
                "Meal Price ($)": 35}, ignore_index=True)

Note – When you add a row to the dataframe using append, you have to specify ignore_index=True otherwise pandas will throw an error. Also if you planning to add a bigger dataframe to another dataframe then use pd.concat() as it is more efficient than append.

1 . Pandas – pd.concat() – How to concat dataframes in pandas

2 . Pandas – pd.merge() – How to merge dataframe in pandas.

Leave a Reply