Example of how to add a new row at the end of a pandas DataFrame in pandas
Table of contents
Create a simple dataframe with pandas
Let's start by creating a simple dataframe df:
>>> import pandas as pd
>>> import numpy as np
>>> data = np.arange(1,13)
>>> data = data.reshape(3,4)
>>> df = pd.DataFrame(data=data,columns=['a','b','c','d'])
>>> df
a b c d
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
Add a row to a dataframe
To add a line to the df dataframe, we can then create a new dataframe:
>>> df_new_line = pd.DataFrame([[10,20,30,40]], columns=['a','b','c','d'] )
>>> df_new_line
a b c d
0 10 20 30 40
and concatenate this one to the dataframe df:
>>> df = pd.concat([df,df_new_line], ignore_index=True)
>>> df
a b c d
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 10 20 30 40
Other possibility use append():
>>> df.append({'a':50,'b':60,'c':70,'d':80}, ignore_index=True)
a b c d
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 10 20 30 40
4 50 60 70 80
References
Links | Site |
---|---|
pandas.DataFrame.append | pandas doc |
Pandas : How to create an empty DataFrame and append rows & columns to it in python | thispointer.com |
Add one row to pandas DataFrame | stackoverflow |