How to Dynamically Add new Rows to a Pandas DataFrame

This is a little trick I used to append new rows to a Pandas DataFrame. This method is similar to appending a new item to a list.

Create an empty DataFrame

df = pd.DataFrame(columns=['A','B'])
df

Add rows by dynamically by leveraging loc[] and len()

The .loc[] method allows you to return a row by identifying the index value. The len() makes this operation dynamic because it will always produce a value 1 greater than the highest index. Because the index doesn’t exist in the DataFrame, Pandas creates a new row. Lastly, pass in the new values as a list to create the new row. Note that the length of your list should be the same as the number of columns in the DataFrame.

df.loc[len(df)] = [1,2]
df

Adding another row is as simple as specifying the values for the next row with a list.

df.loc[len(df)] = [3,4]
df

By passing in one value for the index, Pandas will set that value for the entire row.

df.loc[len(df)] = 'hello'
df

Final Thoughts

Check out more Python tricks in this Colab Notebook or in my recent Python Posts.

Thanks for reading!


Posted

in

by

Tags: