19

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?

0

3 Answers 3

21

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)

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.