Pandas is the most famous data statistics package in the python environment, while DataFrame is translated as a data frame, which is a data organization method. This article mainly introduces pandas in python. dataFrame sums rows and columns and adds new rows and columns. the detailed sample code is provided in this article. For more information, see the following. Pandas is the most famous data statistics package in the python environment, while DataFrame is translated as a data frame, which is a data organization method. This article mainly introduces pandas in python. dataFrame sums rows and columns and adds sample code for new rows and columns. the detailed sample code is provided in this article. For more information, see the following.
This article introduces pandas. DataFrame in python to sum rows and columns and add new rows and columns. I will not talk about it below. let's take a look at the details.
The method is as follows:
Import module:
from pandas import DataFrameimport pandas as pdimport 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 E0 0.673092 0.230338 -0.171681 0.312303 -0.1848131 -0.504482 -0.344286 -0.050845 -0.811277 -0.2981812 0.542788 0.207708 0.651379 -0.656214 0.5075953 -0.249410 0.131549 -2.198480 -0.437407 1.628228
Calculate the total data of each column and add it to the end as a new column
df['Col_sum'] = df.apply(lambda x: x.sum(), axis=1)
Calculates the total data of each row and adds it to the end as a new row.
df.loc['Row_sum'] = df.apply(lambda x: x.sum())
Final data result:
A B C D E Col_sum0 0.673092 0.230338 -0.171681 0.312303 -0.184813 0.8592381 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181 -2.0090712 0.542788 0.207708 0.651379 -0.656214 0.507595 1.2532563 -0.249410 0.131549 -2.198480 -0.437407 1.628228 -1.125520Row_sum 0.461987 0.225310 -1.769627 -1.592595 1.652828 -1.022097
Related articles:
Sample code of how pandas. DataFrame excludes specific rows in python
Pandas. DataFrame (create, index, add and delete) in python
In python, the pandas. DataFrame sums rows and columns and adds new rows and column sample code. For more information, see other related articles in the first PHP community!