Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to slice a field and achieve cumulative summation by Python

Shulou Source: shulou.com Published: 2022-05-31 14:16:54 10月02日 Update

This article mainly introduces Python how to slice a field and achieve cumulative summation of the relevant knowledge, the content is detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that after reading this Python how to slice a field and achieve the cumulative sum of the article will have a harvest, let's take a look.

Question: group according to the first column, add the above accumulation to the following grouping, how to achieve?

Train of thought:

1. First pivot perspective, scale is extended to multiple columns

2.cumsum () accumulation

3.melt reverse perspective, restore the original shape

Load the data source:

Import pandas as pddf = pd.read_table (r "D:\ Jupyter\ data\ df_test.txt") df

Data cleaning process:

Years = [before 1980', '1980-1989', '1990-1999', '2000-2009', '2010-2020'] result = (df.pivot (index= "period", columns= "scale", values= "count") .loc [years] .Cumsum () .reset _ index () .melt (id_vars='period') Value_name='count') result.dropna (inplace=True) result ["count"] = result ["count"] .astype ("int16") result.period = result.period.astype ("category") result.period = result.period.cat.reorder_categories (years) result.sort_values (by= ["period", "scale"], inplace=True) result

This is the end of the article on "how to slice a field and achieve a cumulative sum by Python". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to slice a field and achieve cumulative summation by Python". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Fields knowledge content data articles facets groups values originals shapes ideas easy to operate data sources articles easy to understand more look industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Information MariaDB MySQL vpn