How to append a list to a Pandas DataFrame using iloc in Python?


The iloc method is an integer-location based indexing for selection by position. We are using iloc to append a list to a DataFrame.

Let us first create a DataFrame. The data is in the form of lists of team rankings for our example −

# data in the form of list of team rankings
Team = [['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, columns=['Country', 'Rank', 'Points'])

Following is the row to be appended −

myList = ["Sri Lanka", 7, 30]

Append the above row using iloc(). 5 means index 6 i.e. position 6 row will get replaced with the above new row −

dataFrame.iloc[5] = myList

Example

Following is the code −

import pandas as pd

# data in the form of list of team rankings
Team = [['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, columns=['Country', 'Rank', 'Points'])

print"DataFrame...\n",dataFrame

# row to be appended
myList = ["Sri Lanka", 7, 30]

# append the above row using iloc()
# 5 means index 6 i.e. position 6 row will get replaced with the above new row
dataFrame.iloc[5] = myList

# display the update dataframe
print"\nUpdated DataFrame after appending a row using iloc...\n",dataFrame

Output

This will produce the following output −

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

Updated DataFrame after appending a row using iloc...
       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    Sri Lanka      7       30

Updated on: 22-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements