Salih
Salih

Reputation: 719

Pandas Adding Row with All Values Zero

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?

Upvotes: 19

Views: 34628

Answers (3)

mouwsy
mouwsy

Reputation: 1933

You could take a row from the dataframe, replace it with zeros and then concat it:

import pandas as pd

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

df = pd.concat([df, df.head(1).map(lambda x: 0)], ignore_index=True)

Upvotes: 0

Justin C.
Justin C.

Reputation: 382

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

Upvotes: 5

jezrael
jezrael

Reputation: 862511

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)

Upvotes: 21

Related Questions