Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to append a list to a Pandas DataFrame using loc in Python?
The DataFrame.loc accessor is used to access a group of rows and columns by label or a boolean array. We can use it to append a list as a new row to an existing DataFrame by specifying the next available index position.
Creating the Initial DataFrame
Let us first create a DataFrame with team ranking data ?
import pandas as pd
# Data in the form of list of team rankings
team_data = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75],
['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]
# Creating a DataFrame and adding columns
dataFrame = pd.DataFrame(team_data, columns=['Country', 'Rank', 'Points'])
print("Original DataFrame:")
print(dataFrame)
Original DataFrame:
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
4 South Africa 5 50
5 Bangladesh 6 40
Appending a List Using loc
To append a new row, we use len(dataFrame) as the index position, which gives us the next available row index ?
import pandas as pd
# Data in the form of list of team rankings
team_data = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75],
['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]
# Creating a DataFrame
dataFrame = pd.DataFrame(team_data, columns=['Country', 'Rank', 'Points'])
# Row to be appended as a list
new_team = ["Sri Lanka", 7, 30]
# Append the row using loc
dataFrame.loc[len(dataFrame)] = new_team
print("Updated DataFrame after appending:")
print(dataFrame)
Updated DataFrame after appending:
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
4 South Africa 5 50
5 Bangladesh 6 40
6 Sri Lanka 7 30
How It Works
The loc accessor works by:
-
len(dataFrame)returns the current number of rows (6 in our case) - This becomes the index for the new row (index 6)
- The list values are assigned to the corresponding columns in order
Multiple Rows Appending
You can append multiple rows by incrementing the index ?
import pandas as pd
# Original DataFrame
team_data = [['India', 1, 100], ['Australia', 2, 85]]
dataFrame = pd.DataFrame(team_data, columns=['Country', 'Rank', 'Points'])
# Append multiple rows
dataFrame.loc[len(dataFrame)] = ["England", 3, 75]
dataFrame.loc[len(dataFrame)] = ["New Zealand", 4, 65]
print("DataFrame with multiple appended rows:")
print(dataFrame)
DataFrame with multiple appended rows:
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
Conclusion
Using DataFrame.loc[len(dataFrame)] = list is an efficient way to append a single row to a DataFrame. The len() function automatically provides the next available index position for the new row.
Advertisements
