• pandas(四)唯一值、值计数以及成员资格


    针对Series对象,从中抽取信息

    unique可以得到Series对象的唯一值数组

    >>> obj = Series(['c','a','d','a','a','b','b','c','c'])
    >>> obj.unique()
    array(['c', 'a', 'd', 'b'], dtype=object)
    >>> obj
    0    c
    1    a
    2    d
    3    a
    4    a
    5    b
    6    b
    7    c
    8    c
    dtype: object
    >>> type(obj.unique())
    <class 'numpy.ndarray'>#注意这里返回的不再是Series对象,而是ndarray的一维数组

    返回的是未排序的数组,如果需要排序,再次执行sort()方法或者用numpy的顶级函数sort()

    >>> new_array = obj.unique()
    >>> new_array
    array(['c', 'a', 'd', 'b'], dtype=object)
    >>> new_array.sort()
    >>> new_array
    array(['a', 'b', 'c', 'd'], dtype=object)
    >>> import numpy as np
    >>> new_array = obj.unique()
    >>> new_array
    array(['c', 'a', 'd', 'b'], dtype=object)
    >>> na = np.sort(new_array)
    >>> na
    array(['a', 'b', 'c', 'd'], dtype=object)

    值计数

    用到value_counts方法或value_count顶级函数

    >>> obj
    0    c
    1    a
    2    d
    3    a
    4    a
    5    b
    6    b
    7    c
    8    c
    dtype: object
    >>> obj_c= obj.value_counts()
    >>> obj_c
    c    3
    a    3
    b    2
    d    1
    dtype: int64
    >>> pd.value_counts(obj)#默认是降序
    c    3
    a    3
    b    2
    d    1
    dtype: int64
    >>> pd.value_counts(obj,sort =False)#对统计结果不排序
    a    3
    b    2
    d    1
    c    3
    dtype: int64

    isin用于判断矢量化集合的成员资格,可以用于选取Series或DataFrame列中的数据子集

    >>> mask = obj.isin(['a','c'])
    >>> mask
    0     True
    1     True
    2    False
    3     True
    4     True
    5    False
    6    False
    7     True
    8     True
    dtype: bool
    >>> obj[mask]
    0    c
    1    a
    3    a
    4    a
    7    c
    8    c
    dtype: object

    可以将value_counts的顶级函数传给DataFrame对象的apply()使用,以便统计一列或者一行的值的个数

  • 相关阅读:
    [Linux] Nginx服务下统计网站的QPS
    [Go] go等待读取最后一行的数据内容
    [Go] Golang中的面向对象
    [Linux] 常见的并发模型
    [PHP] pmap可以查看进程占用内存的详细情况
    [PHP] 解决php中上传大文件的错误
    [PHP] 循环查看php-fpm的内存占用情况
    [Go] go中的goto语句跳到指定标签
    Java抽象类(Abstract Class)与接口(Interface)区别
    Java访问级别修饰符
  • 原文地址:https://www.cnblogs.com/zuoshoushizi/p/8734027.html
Copyright © 2020-2023  润新知