Pandas Adding Row with All Values Zero

Viewed 22046

If I have a following dataframe:

          A       B       C       D       E

1         1       2       0       1       0
2         0       0       0       1      -1
3         1       1       3      -5       2
4        -3       4       2       6       0
5         2       4       1       9      -1
6         1       2       2       4       1

How can i add a row end of the dataframe with all values "0 (Zero)"?

Desired Output is;

          A       B       C       D       E

1         1       2       0       1       0
2         0       0       0       1      -1
3         1       1       3      -5       2
4        -3       4       2       6       0
5         2       4       1       9      -1
6         1       2       2       4       1
7         0       0       0       0       0

Could you please help me about this?

2 Answers

Use Setting with enlargement:

df.loc[len(df)] = 0
print (df)
   A  B  C  D  E
1  1  2  0  1  0
2  0  0  0  1 -1
3  1  1  3 -5  2
4 -3  4  2  6  0
5  2  4  1  9 -1
6  0  0  0  0  0

Or DataFrame.append with Series filled by 0 and index by columns of DataFrame:

df = df.append(pd.Series(0, index=df.columns), ignore_index=True)

Create a new dataframe of zeroes using the shape and column list of the current. Then append:

df = pd.DataFrame([[1, 2], [3, 4],[5,6]], columns=list('AB'))
print(df)
   A  B
0  1  2
1  3  4
2  5  6

df2 = pd.DataFrame([[0]*df.shape[1]],columns=df.columns)
df = df.append(df2, ignore_index=True)
print(df)
   A  B
0  1  2
1  3  4
2  5  6
3  0  0
Related