Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
Salih Avatar asked Oct 17 '19 13:10

Salih


People also ask

How do I add a row of zeros to a DataFrame?

Use concat() to Add a Row at Top of DataFrame Use pd. concat([new_row,df. loc[:]]). reset_index(drop=True) to add the row to the first position of the DataFrame as Index starts from zero.

How do I sum an entire row in pandas?

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.

How do I add blank rows to a DataFrame in Python?

We will first create a DataFrame and then we will add an empty row by using the concat() method or append() method, inside this method we will pass an empty Series such that it does not hold any value. Adding a series will add 1 null value to each column and hence we will end up adding an extra row with the null value.


2 Answers

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
like image 25
Justin C. Avatar answered Sep 21 '22 18:09

Justin C.


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)

like image 192
jezrael Avatar answered Sep 19 '22 18:09

jezrael