Append Row to pandas DataFrame in Python (Example Code)

In this Python programming tutorial you’ll learn how to insert a new row to a pandas DataFrame.

Preparing the Example

import pandas as pd                                         # Import pandas library in Python
my_df = pd.DataFrame({'A':['x', 'y', 'x', 'y', 'z', 'z'],  # Construct example DataFrame
                      'B':['g', 'g', 'w', 'a', 'g', 'f'],
                      'C':['a', 'b', 'c', 'd', 'e', 'f']})
print(my_df)                                               # Display example DataFrame in console
#    A  B  C
# 0  x  g  a
# 1  y  g  b
# 2  x  w  c
# 3  y  a  d
# 4  z  g  e
# 5  z  f  f
my_row = ['lala', 'lele', 'lili']                          # Construct new row

Example: Add Row to pandas DataFrame Using loc Attribute

my_df.loc[6] = my_row                                      # Adding new row
print(my_df)                                               # Display new DataFrame
#       A     B     C
# 0     x     g     a
# 1     y     g     b
# 2     x     w     c
# 3     y     a     d
# 4     z     g     e
# 5     z     f     f
# 6  lala  lele  lili

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top