How to append a list as a row to a Pandas DataFrame in Python?
Prerequisite: Pandas DataFrame
In this article, We are going to see how to append a list as a row to a pandas dataframe in Python. It can be done in three ways:
Append list using loc[] methods
Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
Let’s append the list with step-wise:
Step 1: Create a simple dataframe using the list.
Python3
import pandas as pd
Person = [ [ 'Satyam' , 21 , 'Patna' , 'India' ],
[ 'Anurag' , 23 , 'Delhi' , 'India' ],
[ 'Shubham' , 27 , 'Coimbatore' , 'India' ]]
df = pd.DataFrame(Person,
columns = [ 'Name' , 'Age' , 'City' , 'Country' ])
display(df)
|
Output:
Step 2: Using loc to append the new list to a data frame.
Python3
list = [ "Saurabh" , 23 , "Delhi" , "india" ]
df.loc[ len (df)] = list
display(df)
|
Output:
Append list using iloc[] methods
Pandas DataFrame.iloc method access integer-location based indexing for selection by position.
Example:
Python3
import pandas as pd
Person = [ [ 'Satyam' , 21 , 'Patna' , 'India' ],
[ 'Anurag' , 23 , 'Delhi' , 'India' ],
[ 'Shubham' , 27 , 'Coimbatore' , 'India' ],
[ "Saurabh" , 23 , "Delhi" , "india" ]]
df = pd.DataFrame(Person,
columns = [ 'Name' , 'Age' , 'City' , 'Country' ])
list = [ 'Ujjawal' , 22 , 'Fathua' , 'India' ]
df.iloc[ 2 ] = list
display(df)
|
Output:
Note – It is used for location-based indexing so it works for only the existing index and replaces the row element.
Append list using append() methods
Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object.
Example:
Python3
import pandas as pd
Person = [ [ 'Satyam' , 21 , 'Patna' , 'India' ],
[ 'Anurag' , 23 , 'Delhi' , 'India' ],
[ 'Shubham' , 27 , 'Coimbatore' , 'India' ]]
df = pd.DataFrame(Person,
columns = [ 'Name' , 'Age' , 'City' , 'Country' ])
list = [[ "Manjeet" , 25 , "Delhi" , "india" ]]
df = df.append(pd.DataFrame( list ,
columns = [ 'Name' , 'Age' , 'City' , 'Country' ]),
ignore_index = True )
display(df)
|
Output:
Time complexity:
Appending a dataframe to another dataframe is a constant time operation, as it requires only the addition of one row (or multiple rows) to the existing dataframe. Hence the time complexity of this operation is O(1).
Space complexity:
The space complexity of this operation is also O(1), as it only requires the addition of one row of data to the existing dataframe.
Last Updated :
02 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...