How to add n rows at the end of a pandas dataframe of 0 values?

Question:

I have a dataframe like

    address     balance
0   0xa04fc9    1136151.200472032
1   0x1937c5    1000000.0
2   0xff7843    933580.0
3   0x528173    660354.97467932
4   0x6eb557    660000.0
5   0x198ef1    608334.724
6   0x1b3cb8    560000.0
7   0x51f9c4    530000.0
8   0x2b717c    500000.0
.         ...

I want to add, let’s say, 20 rows at the end of the data frame such that

    address     balance           
0   0xa04fc9    1136151.200472032  
1   0x1937c5    1000000.0 
2   0xff7843    933580.0
3   0x528173    660354.97467932
4   0x6eb557    660000.0
5   0x198ef1    608334.724
6   0x1b3cb8    560000.0
7   0x51f9c4    530000.0
8   0x2b717c    500000.0
.                 0
.                 0
.                 0
.                 0
28                0

Any help will be appreciated!

Asked By: Olive

||

Answers:

Use concat with DataFrame constructor:

df = pd.concat([df, 
                pd.DataFrame(0, columns=['balance'], index=range(20))], ignore_index=True)
print (df)
     address       balance
0   0xa04fc9  1.136151e+06
1   0x1937c5  1.000000e+06
2   0xff7843  9.335800e+05
3   0x528173  6.603550e+05
4   0x6eb557  6.600000e+05
5   0x198ef1  6.083347e+05
6   0x1b3cb8  5.600000e+05
7   0x51f9c4  5.300000e+05
8   0x2b717c  5.000000e+05
9        NaN  0.000000e+00
10       NaN  0.000000e+00
11       NaN  0.000000e+00
12       NaN  0.000000e+00
13       NaN  0.000000e+00
14       NaN  0.000000e+00
15       NaN  0.000000e+00
16       NaN  0.000000e+00
17       NaN  0.000000e+00
18       NaN  0.000000e+00
19       NaN  0.000000e+00
20       NaN  0.000000e+00
21       NaN  0.000000e+00
22       NaN  0.000000e+00
23       NaN  0.000000e+00
24       NaN  0.000000e+00
25       NaN  0.000000e+00
26       NaN  0.000000e+00
27       NaN  0.000000e+00
28       NaN  0.000000e+00
Answered By: jezrael

you can also use the df.reindex() method
say you need to add 5 new rows to you df dataframe with 0 as value

df = df.reindex([*range(len(df)+5)],fill_value = 0)
Answered By: Stefano Verugi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.