How to create an empty data frame with pandas and add new entries row by row ?

How to create an empty data frame with pandas and add new entries row by row ?

Daidalos April 15, 2020


Example of how to create an empty data frame with pandas and add new entries row by row in python:

Create an empty data frame

Let's create an empty data frame with pandas:

>>> import pandas as pd
>>> df1 = pd.DataFrame(columns=['a','b','c','d'])
>>> df1
Empty DataFrame
Columns: [a, b, c, d]
Index: []

Check the number of rows:

>>> len(df1)
0

Check the number of columns:

>>> len(df1.columns)
4

Add new row with concat()

Now, to add a new row a solution is to use concat():

>>> df_new_row = pd.DataFrame(data=np.array([[1,2,3,4]]), columns=['a','b','c','d'])
>>> df1 = pd.concat([df1,df_new_row], ignore_index=True)
>>> df1
   a  b  c  d
0  1  2  3  4

Add another row

 >>> df_new_row = pd.DataFrame(data=np.array([[21,24,37,45]]), columns=['a','b','c','d'])
 >>> df1 = pd.concat([df1,df_new_row], ignore_index=True)
 >>> df1
    a   b   c   d
0   1   2   3   4
1  21  24  37  45

Add new row with append()

Another solution is to use append():

>>> new_row = {'a':31,'b':32,'c':33,'d':34}
>>> df1.append(new_row, ignore_index=True)
    a   b   c   d
0   1   2   3   4
1  21  24  37  45
2  31  32  33  34

References

Links Site
Python pandas: fill a dataframe row by row stackoverflow