How to Insert a Row in a Pandas DataFrame in Python
There are different options to insert a rows in a Pandas DataFrame in Python. In this article, I’ll show you various approaches to insert a row in a Pandas DataFrame in Python. I have an another article How to Create a Pandas DataFrame in Python, where you will learn how to create a DataFrame. In this tutorial, I’ll use the below sample DataFrame:
id name math_score 0 202301 Minhaj 92 1 202302 Ridhwan 86 2 202303 Tanveer 76 3 202304 Sharodia 89 4 202305 Alve 99 5 202306 Intisar 99
In Pandas, you can insert a new row into a DataFrame using the loc
indexer or the concat
function.
Using the loc
indexer:
import pandas as pd
# Insert a new row at index 0
df.loc[0] = [202307,'Fahim','100']
print(df)
Output:
id name math_score 0 202307 Fahim 100 1 202302 Ridhwan 86 2 202303 Tanveer 76 3 202304 Sharodia 89 4 202305 Alve 99 5 202306 Intisar 99
In the above code you see that new row/record will replace the existing index’s row/record. So, index method insert a new row and as well as replace the existing one.
Using the concat function:
import pandas as pd
# Create a new DataFrame with the new row
new_row = pd.DataFrame({'id': [202308], 'name': ['Fayeza'],'math_score': [98]})
# Concatenate the two DataFrames
df = pd.concat([new_row, df], ignore_index=True)
print(df)
Output:
id name math_score 0 202308 Fayeza 98 1 202307 Fahim 100 2 202302 Ridhwan 86 3 202303 Tanveer 76 4 202304 Sharodia 89 5 202305 Alve 99 6 202306 Intisar 99
You can also use append()
function to add a new row.
import pandas as pd
# Create a new DataFrame with the new row
new_row = pd.DataFrame({'id': [202301], 'name': ['Minhaj'],'math_score': [92]})
df = df.append(new_row, ignore_index=True)
print(df)
Output:
id name math_score 0 202308 Fayeza 98 1 202307 Fahim 100 2 202302 Ridhwan 86 3 202303 Tanveer 76 4 202304 Sharodia 89 5 202305 Alve 99 6 202306 Intisar 99 7 202301 Minhaj 92
It is important to mention that these methods will insert a new row at the end of the DataFrame by default, if you need to insert the new row at a specific position you can use the .iloc
property to select the row where you want to add the new row.
In this tutorial, I tried to brief how to insert a row in a Pandas DataFrame in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.