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

时间:2021-01-08 22:00:00

针对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()使用,以便统计一列或者一行的值的个数