Home  >  Article  >  Backend Development  >  Sample code for summing rows and columns and adding new rows and columns in pandas.DataFrame in python

Sample code for summing rows and columns and adding new rows and columns in pandas.DataFrame in python

高洛峰
高洛峰Original
2017-03-25 13:39:535205browse

pandas is the most famous data statistics package in the python environment, and DataFrame is translated as data frame, which is a way of organizing data. This article mainly introduces you to the summation of rows and columns in pandas.DataFrame in python. Add a new row and column sample code. The article provides detailed sample code. Friends in need can refer to it. Let's take a look together.

This article introduces the relevant information about summing rows and columns and adding new rows and columns in pandas.DataFrame in python. I won’t say much below, let’s take a look at the detailed introduction.

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 data in each column and add it to the end as a new column

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

Calculate the sum of the data in each row and add 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_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

Related articles:

Detailed explanation of pandas.DataFrame in python to exclude specific rows sample code

pandas.DataFrame in python (creation, indexing, addition and deletion) Introduction to simple operation methods

The above is the detailed content of Sample code for summing rows and columns and adding new rows and columns in pandas.DataFrame in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn