In python pandas.DataFrame sums up rows and columns and adds a new row and column example


This article describes the sum of rows and columns in python (pandas.DataFrame) and the information about adding new rows and columns.

The method is as follows:

Import module:

from pandas import DataFrame
import pandas as pd
import numpy as np

Generate DataFrame data

df = DataFrame(np.random.randn(4, 5), columns=['A', 'B', 'C', 'D', 'E'])

DataFrame data preview:

  A  B  C  D  E
0 0.673092 0.230338 -0.171681 0.312303 -0.184813
1 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181
2 0.542788 0.207708 0.651379 -0.656214 0.507595
3 -0.249410 0.131549 -2.198480 -0.437407 1.628228

Calculate the sum of the columns and add it to the end as a new column

df['Col_sum'] = df.apply(lambda x: x.sum(), axis=1)

Calculates the sum of the rows and adds them to the end as a new row

df.loc['Row_sum'] = df.apply(lambda x: x.sum())

Final data results:

  A  B  C  D  E Col_sum
0 0.673092 0.230338 -0.171681 0.312303 -0.184813 0.859238
1 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181 -2.009071
2 0.542788 0.207708 0.651379 -0.656214 0.507595 1.253256
3 -0.249410 0.131549 -2.198480 -0.437407 1.628228 -1.125520
Row_sum 0.461987 0.225310 -1.769627 -1.592595 1.652828 -1.022097

conclusion