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?
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With