How to add rows to the Pandas DataFrame

Renesh Bedre    2 minute read

In this article, you will learn multiple ways to add rows to the existing Pandas DataFrame

Let’s first create random Pandas DataFrame (you can also import pandas DataFrame from file)

import pandas as pd
df = pd.DataFrame({'col1':['A', 'B', 'C'], 'col2':[1, 2, 3], 'col3':[0.1, 0.2, 0.3], 
                   'col4':[True, False, True]})
df
# output
  col1  col2  col3   col4
0    A     1   0.1   True
1    B     2   0.2  False
2    C     3   0.3   True

1. Add row using loc

Rows can be added to existing Pandas DataFrame using loc. The loc requires the last index number to add the row. If you provide a between index number, the given row with the index number will be replaced.

# add rows at end of DataFrame
new_row = ['D', 4, 0.4, False]
df.loc[df.index.size] = new_row
df
# output
  col1  col2  col3   col4
0    A     1   0.1   True
1    B     2   0.2  False
2    C     3   0.3   True
3    D     4   0.4  False

Add row value at the specific column,

# add value 4 in col2
df.loc[df.index.size, "col2"] = 4
df
# output
  col1  col2  col3   col4
0    A   1.0   0.1   True
1    B   2.0   0.2  False
2    C   3.0   0.3   True
3  NaN   4.0   NaN    NaN

2. Add row using concat method

You can append another DataFrame to the existing DataFrame using the concat method

# create another DataFrame
df2 = pd.DataFrame({'col1':['D', 'E'], 'col2':[4, 5], 'col3':[0.4, 0.5], 'col4':[True, False]})

Append df and df2,

pd.concat([df, df2])
# output
  col1  col2  col3   col4
0    A     1   0.1   True
1    B     2   0.2  False
2    C     3   0.3   True
0    D     4   0.4   True
1    E     5   0.5  False

Note: Pandas append method is deprecated since version 1.4.0. concat is recommended over the append method.

3. Replace existing row using iloc

iloc may not work with adding a new row at the end of DataFrame, but it could be useful to replace an existing row in a Dataframe

new_row = ['E', 5, 0.5, False]
df.iloc[1] = new_row
df
# output
  col1  col2  col3   col4
0    A     1   0.1   True
1    E     5   0.5  False
2    C     3   0.3   True

Enhance your skills with courses on Python and pandas

This work is licensed under a Creative Commons Attribution 4.0 International License

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Tags:

Updated: