About Python in pandas. Dataframe add a new row and column to the row and column sample code

Source: Internet
Author: User
Pandas is the most famous data statistics package in Python environment, and Dataframe is a data frame, which is a kind of data organization, this article mainly introduces the pandas in Python. Dataframe the row and column summation and add new row and column sample code, the text gives the detailed sample code, the need for friends can refer to, let's take a look at it.

This article describes the pandas in Python. Dataframe the row and column summation and add new rows and columns of the relevant information, the following words do not say, to see the detailed introduction.

Here's how:

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 sum of each column's data 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 each row's data and adds it 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_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.1984 80-0.437407 1.628228-1.125520row_sum 0.461987 0.225310-1.769627-1.592595 1.652828-1.022097

Related articles:

Detailed in Python pandas. Dataframe example code to exclude a specific line method

Python in Pandas. Brief introduction to DataFrame (Create, index, add and delete)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.