Skip to content

Acing Python: Effortlessly Add Row to Dataframe

[

Adding Rows to a DataFrame

In this tutorial, we will learn how to add rows to a DataFrame in Python using the Pandas library. We will cover the concept of the .loc attribute for indexing and demonstrate how to insert rows using this method.

Step 1: Importing the Required Libraries

To get started, we need to import the necessary libraries. We will be using the Pandas library for working with DataFrames. Open your Python editor and import the library as follows:

import pandas as pd

Step 2: Creating a DataFrame

Next, let’s create a sample DataFrame to work with. We will use the pd.DataFrame() function and pass a dictionary as the data source. Each key-value pair in the dictionary will represent a column of the DataFrame. Here’s an example:

data = {'Name': ['John', 'Mike', 'Sarah'],
'Age': [25, 30, 35],
'City': ['New York', 'Chicago', 'Los Angeles']}
df = pd.DataFrame(data)
print(df)

This will create a DataFrame with three columns: “Name”, “Age”, and “City”. The output will display the DataFrame:

Name Age City
0 John 25 New York
1 Mike 30 Chicago
2 Sarah 35 Los Angeles

Step 3: Adding Rows to a DataFrame using .loc

Now, let’s learn how to add rows to our DataFrame using the .loc attribute. This method allows us to insert rows using labels from the index.

To begin, we first need to create a new DataFrame called df2 using the pd.DataFrame() function. Here’s the code:

df2 = pd.DataFrame({'Name': ['Emily', 'David'],
'Age': [20, 22],
'City': ['Boston', 'Seattle']})

This will create a DataFrame df2 with two rows: “Emily” and “David”.

To add these rows to our original DataFrame df, we can use the .loc method. Let’s insert the rows at position 2 by changing the index label to [60, 50, 40]:

df.loc[2] = [60, 50, 40]
print(df)

The output will show the updated DataFrame with the new rows added:

Name Age City
0 John 25 New York
1 Mike 30 Chicago
2 60 50 40

Step 4: Making an Index labeled 2 and adding new values

You can also make an index labeled 2 and add new values to the DataFrame. Let’s demonstrate this by creating another DataFrame called df3:

df3 = pd.DataFrame({'Name': ['Lily', 'Ben'],
'Age': [28, 32],
'City': ['San Francisco', 'Houston']})

This will create a DataFrame df3 with two rows: “Lily” and “Ben”.

To add these rows to df using the .loc method, we can run the following code:

df.loc[2] = [11, 12, 13]
print(df)

The output will display the updated DataFrame with the new rows added:

Name Age City
0 John 25 New York
1 Mike 30 Chicago
2 11 12 13

Conclusion

In this tutorial, we learned how to add rows to a DataFrame in Python using the Pandas library. We explored the concept of the .loc attribute for indexing and demonstrated how to insert rows using this method. By following the provided step-by-step instructions and running the sample codes, you should now be able to add rows to DataFrames with ease in Python.