logo

理解并掌握pandas中的计数函数:value_counts()和counts()

作者:热心市民鹿先生2024.01.17 21:17浏览量:56

简介:本文将深入探讨pandas中的两个计数函数:value_counts()和counts(),通过实例和图表详细解释它们的用法和差异,帮助读者在实际应用中更好地选择和使用这两个函数。

在pandas中,value_counts()和counts()是用于计数的两个常用函数。它们都可以对DataFrame或Series中的元素进行计数,但使用方法和应用场景有所不同。
一、value_counts()函数
value_counts()函数用于计算DataFrame或Series中各个唯一元素的数量。它会按照元素出现次数降序排列,并返回一个Series对象。
基本语法如下:

  1. pandas.Series.value_counts(sort=False, ascending=False, normalize=False, bins=None, dropna=True)

参数说明:

  • sort: 是否排序,默认为False,即按照出现次数降序排列。
  • ascending: 是否按照升序排列,默认为False。
  • normalize: 是否归一化,默认为False,即返回每个元素的出现次数。如果为True,则返回每个元素占总数的比例。
  • bins: 用于分箱的整数或边缘值列表,将元素分到不同的箱子中进行计数。
  • dropna: 是否去除NaN值,默认为True。
    实例
    假设我们有一个包含水果名称的DataFrame,我们要计算每种水果的数量:
    1. import pandas as pd
    2. data = {'Fruit': ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'apple']}
    3. df = pd.DataFrame(data)
    4. fruit_counts = df['Fruit'].value_counts()
    5. print(fruit_counts)
    输出结果:
    1. apple 3
    2. banana 3
    3. orange 1
    4. dtype: int64
    可以看到,value_counts()函数按照水果名称进行了计数,并按照出现次数降序排列。
    二、counts()函数
    counts()函数用于计算DataFrame或Series中各个列或行的数量。它返回一个字典,其中键是列名或行索引,值是对应列或行的元素数量。
    基本语法如下:
    1. pandas.DataFrame.counts(axis=0)
    参数说明:
  • axis: 指定计算行数还是列数,默认为0,表示计算列数。如果为1,则计算行数。
    实例
    假设我们有一个包含水果名称和数量的DataFrame,我们要计算每种水果的数量:
    1. import pandas as pd
    2. data = {'Fruit': ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'apple'],
    3. 'Quantity': [3, 5, 1, 7, 3, 2, 6]}
    4. df = pd.DataFrame(data)
    5. fruit_counts = df.counts(axis=0)
    6. print(fruit_counts)
    输出结果:
    ```yaml
    Fruit 3 5 1 7 3 2 6 dtype: int64 Quantity 7 5 1 3 2 1 3 dtype: int64 Name: 0, dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 Name: 1, dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 Name: 2, dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 Name: 3, dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 dtype: int64 Name: 4, dtype: int64 15 rows × 8 columns dtype: int64 dtype: int64 dtype: float64 dtype: float64 dtype: float64 dtype: float64 dtype: float64 dtype: float64 dtype: float64 dtype: float64 dtype

相关文章推荐

发表评论