Add a row at top in pandas DataFrame


In Pandas a DataFrame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can create a DataFrame using list, dict, series and another DataFrame. But when we want to add a new row to an already created DataFrame, it is achieved through a in-built method like append which add it at the end of the DataFrame. In this article we will find ways to add the new row DataFrame at the top of the DataFrame using some tricks involving the index of the elements in the DataFrame.

Example

Let's first create a new DataFrame in Pandas shown as below.

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
print df

Output

Running the above code gives us the following result -

Age       Gender      Name
0         28          MTom
1         34          MJack
2         29          FMary
3         42          F Ricky

Approach 1 - The first approach we follow to add a new row at the top of the above DataFrame is to convert the new incoming row to a DataFrame and concat it with the existing DataFrame while resetting the index values. Because of Index reset the new row gets added at the top.

Example

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
top_row = pd.DataFrame({'Name':['Lavina'],'Age':[2],'Gender':['F']})
# Concat with old DataFrame and reset the Index.
df = pd.concat([top_row, df]).reset_index(drop = True)
print df

Output

Running the above code gives us the following result -

         Age       Gender      Name
0         2          F         Lavina
1         28         M         Tom
2         34         M         Jack
3         29         F         Mary
4         42         F         Ricky

Approach 2 - In this approach we use the Dataframe.iloc[] method which allows us to add a new row at the index position 0. In the below example we are adding a new row as a list by mentioning the index value for the .loc method as 0 which is the index value for the first row.

Example

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
# Add a new row at index position 0 with values provided in list
df.iloc[0] = ['7', 'F','Piyu']
print df

Output

Running the above code gives us the following result:

      Age    Gender   Name
0      7      F       Piyu
1      34     M       Jack
2      29     F       Mary
3      42     F       Ricky
raja
Published on 07-Aug-2019 11:03:33
Advertisements