📜  pandas groupby sum - Python (1)

📅  最后修改于: 2023-12-03 15:03:28.321000             🧑  作者: Mango

Pandas Groupby和Sum介绍

Pandas是一种Python库,用于数据分析和数据操作。它支持各种数据操作,如过滤、排序、合并、分组和聚合。其中,Pandas Groupby和Sum是非常重要的功能。

Pandas Groupby

Pandas Groupby是一种分组操作,它可根据给定的条件,对数据进行分组处理。分组操作可以分别针对不同的分组,应用不同的聚合函数。这样就可以对一个大型数据集进行分组处理,并按组展示数据。

以下是一个简单的Groupby示例:

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
                         'foo', 'bar', 'foo', 'foo'],
                   'B': ['one', 'one', 'two', 'three',
                         'two', 'two', 'one', 'three'],
                   'C': [1, 2, 3, 4, 5, 6, 7, 8],
                   'D': [10, 20, 30, 40, 50, 60, 70, 80]})

grouped = df.groupby('A')

for name, group in grouped:
    print(name)
    print(group)

在这个例子中,我们将数据按'A'列进行分组,然后在每个组内输出它的内容。

Pandas Sum

Pandas Sum指的是对数据的求和操作。它的应用范围非常广泛,比如可以对DataFrame或Series的数据进行求和操作。以下是一个Sum的简单示例:

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
                         'foo', 'bar', 'foo', 'foo'],
                   'B': ['one', 'one', 'two', 'three',
                         'two', 'two', 'one', 'three'],
                   'C': [1, 2, 3, 4, 5, 6, 7, 8],
                   'D': [10, 20, 30, 40, 50, 60, 70, 80]})

df_sum = df[['C', 'D']].sum()

print(df_sum)

在这个例子中,我们对DataFrame的'C'列和'D'列进行求和操作,然后输出结果。

Pandas Groupby和Sum结合

Pandas Groupby和Sum结合在一起可以非常方便地进行数据聚合操作。以下是一个示例:

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
                         'foo', 'bar', 'foo', 'foo'],
                   'B': ['one', 'one', 'two', 'three',
                         'two', 'two', 'one', 'three'],
                   'C': [1, 2, 3, 4, 5, 6, 7, 8],
                   'D': [10, 20, 30, 40, 50, 60, 70, 80]})

grouped = df.groupby('A')

df_sum = grouped[['C', 'D']].sum()

print(df_sum)

在这个例子中,我们先将数据按'A'列进行分组,然后对每个组的'C'列和'D'列进行求和操作,最后输出结果。

以上就是Pandas Groupby和Sum的简单介绍,希望对你有所帮助。