Series第七讲 计算/描述统计(下)

2020-09-23  本文已影响0人  butters001

Series第七讲 计算/描述统计(下)

本节课将讲解Pandas-Series的计算/描述统计,由于接口过多,将分为上下两讲分别进行说明介绍。

计算/描述统计(下)

详细介绍

首先导入所需依赖包

In [1]: import numpy as np                                                               
In [2]: import pandas as pd

1. Series.nlargest()

Series.nlargest(n=5, keep='first')

返回最大的n个元素。

常用参数介绍:
In [8]: s = pd.Series([1, 3, 2, 2, 5, 6, 5], index=[list('abcdefg')])                   
In [9]: s                                                                                                                               
Out[9]: 
a    1
b    3
c    2
d    2
e    5
f    6
g    5
dtype: int64

In [10]: s.nlargest(2)                                                                                                                  
Out[10]: 
f    6
e    5
dtype: int64

In [11]: s.nlargest(2, keep='all')                                                                                                      
Out[11]: 
f    6
e    5
g    5
dtype: int64

2. Series.nsmallest()

Series.nsmallest(n=5, keep='first')

返回最小的n个元素,参数同nlargest()。

In [13]: s.nsmallest(2)                                                                                                                 
Out[13]: 
a    1
c    2
dtype: int64

In [14]: s.nsmallest(2, keep='all')                                                                                                     
Out[14]: 
a    1
c    2
d    2
dtype: int64

3. Series.pct_change()

Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)

默认情况下,计算与前一行的百分比变化。这在比较元素时间序列中的变化百分比时很有用。

常用参数介绍:
In [15]: s = pd.Series([90, 91, 85])                                                                                                    
In [16]: s                                                                                                                              
Out[16]: 
0    90
1    91
2    85
dtype: int64

# 与前一个比较
In [17]: s.pct_change()                                                                                                                 
Out[17]: 
0         NaN
1    0.011111
2   -0.065934
dtype: float64

# 与前面的第二个比较
In [18]: s.pct_change(periods=2)                                                                                                        
Out[18]: 
0         NaN
1         NaN
2   -0.055556
dtype: float64

# 缺失值处理 可以查看之前的 fill_na() 方法
In [19]: s = pd.Series([90, 91, None, 85])                                               
In [20]: s                                                                                                                              
Out[20]: 
0    90.0
1    91.0
2     NaN
3    85.0
dtype: float64

In [21]: s.pct_change(fill_method='ffill')                                                                                              
Out[21]: 
0         NaN
1    0.011111
2    0.000000
3   -0.065934
dtype: float64

# 等同于
In [45]: s.fillna(method='ffill').pct_change()                                  
Out[45]: 
0         NaN
1    0.011111
2    0.000000
3   -0.065934
dtype: float64

4. Series.prod()

Series.prod(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)

每个轴的值的乘积。注意⚠️:空或全为NaN的Series的prod()结果为1,可以通过min_count和skipna参数使结果为NaN。

In [26]: pd.Series([]).prod()                                                           
Out[26]: 1.0

In [27]: pd.Series([]).prod(min_count=1)                                                 
Out[27]: nan

In [32]: pd.Series([np.nan]).prod()                              
Out[32]: 1.0

In [33]: pd.Series([np.nan]).prod(skipna=False)                                       
Out[33]: nan

5. Series.quantile()

Series.quantile(q=0.5, interpolation='linear')

返回给定分位数对应的值。

常用参数介绍:
In [35]: s = pd.Series([1, 2, 3, 4]) 
    ...: s.quantile(.5)                                                                                                                 
Out[35]: 2.5

In [36]: s.quantile([.25, .5, .75])                                                                                                     
Out[36]: 
0.25    1.75
0.50    2.50
0.75    3.25
dtype: float64

6. Series.rank()

Series.rank(axis=0, method='average', numeric_only=None, na_option='keep', ascending=True, pct=False)

沿轴计算数值数据等级(从1到n)。

常用参数介绍:
In [37]: df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog', 
    ...:                                    'spider', 'snake'], 
    ...:                         'Number_legs': [4, 2, 4, 8, np.nan]})          

In [38]: df                                                                     
Out[38]: 
    Animal  Number_legs
0      cat          4.0
1  penguin          2.0
2      dog          4.0
3   spider          8.0
4    snake          NaN

"""
以下示例显示了使用上述参数的方法的行为:
  - default_rank:这是不使用任何参数而获得的默认行为。
  - max_rank:设置具有相同值的记录将使用最高排名进行排名(例如:由于“ cat”和“ dog”都位于第二和第三位置,因此分配了等级3。)method = 'max'
  - NA_bottom:选择,如果存在具有NaN值的记录,则将它们放在排名的底部。na_option = 'bottom'
  - pct_rank:设置时,排名以百分等级表示。pct = True
"""
In [39]: df['default_rank'] = df['Number_legs'].rank() 
    ...: df['max_rank'] = df['Number_legs'].rank(method='max') 
    ...: df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom') 
    ...: df['pct_rank'] = df['Number_legs'].rank(pct=True)                      

In [40]: df                                                                     
Out[40]: 
    Animal  Number_legs  default_rank  max_rank  NA_bottom  pct_rank
0      cat          4.0           2.5       3.0        2.5     0.625
1  penguin          2.0           1.0       1.0        1.0     0.250
2      dog          4.0           2.5       3.0        2.5     0.625
3   spider          8.0           4.0       4.0        4.0     1.000
4    snake          NaN           NaN       NaN        5.0       NaN

7. Series.sem()

Series.sem(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

返回请求轴上的平均值的无偏标准误差

In [36]: pd.Series([1, 1, 2, 3, 5, 8]).sem()                                    
Out[36]: 1.1155467020454342

8. Series.skew()

Series.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

返回请求轴上的偏峰。

In [35]: pd.Series([1, 1, 2, 3, 5, 8]).skew()                                   
Out[35]: 1.1534354656835897

9. Series.std()

Series.std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

计算Series的标准差,排除缺失值。

In [3]: s = pd.Series([1, 3, 2.5, None, 7])                                     

In [4]: s                                                                       
Out[4]: 
0    1.0
1    3.0
2    2.5
3    NaN
4    7.0
dtype: float64

In [5]: s.std()                                                                 
Out[5]: 2.5617376914898995

10. Series.sum()

Series.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)

沿轴计算values的数值和。

In [6]: s.sum()                                                                 
Out[6]: 13.5

11. Series.var()

Series.var(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

计算Series的方差,排除缺失值。

In [7]: s.var()                                                                 
Out[7]: 6.5625

12. Series.kurtosis()

Series.kurtosis(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

同上一篇文章的Series.kurt(),返回请求轴上的无偏峰度。

In [32]: pd.Series([1, 1, 2, 3, 5, 8]).kurt()                                   
Out[32]: 0.5859374999999982

In [34]: pd.Series([1, 1, 2, 3, 5, 8]).kurtosis()                               
Out[34]: 0.5859374999999982

13. Series.unique()

Series.unique()

返回Series对象的唯一值(ndarray)。

In [8]: pd.Series([2, 1, 3, 3], name='A').unique()                              
Out[8]: array([2, 1, 3])

In [9]: pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique()      
Out[9]: array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')

In [10]: pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern') for _ in range(3
    ...: )]).unique()                                                           
Out[10]: 
<DatetimeArray>
['2016-01-01 00:00:00-05:00']
Length: 1, dtype: datetime64[ns, US/Eastern]

# 无序分类将按出现顺序返回类别
In [11]: pd.Series(pd.Categorical(list('baabc'))).unique()                      
Out[11]: 
[b, a, c]
Categories (3, object): [b, a, c]

# 有序的分类会保留类别的排序
In [12]: pd.Series(pd.Categorical(list('baabc'), categories=list('abc'), ordered
    ...: =True)).unique()                                                       
Out[12]: 
[b, a, c]
Categories (3, object): [a < b < c]

14. Series.nunique()

Series.nunique(dropna=True)

返回对象中唯一元素的数量,默认不包含缺失值。

# 描述一个数值型的Series
In [13]: s = pd.Series([1, 3, 5, 7, 7])                                         
In [14]: s                                                                      
Out[14]: 
0    1
1    3
2    5
3    7
4    7
dtype: int64

In [15]: s.nunique()                                                            
Out[15]: 4

15. Series.is_unique

Series.is_unique

属性,如果Series里的值唯一则返回True。

In [18]: pd.Series([1, 3, 5, 7, 7]).is_unique                                   
Out[18]: False

In [19]: pd.Series([1, 3, 5, 7]).is_unique                                      
Out[19]: True

16. Series.is_monotonic

Series.is_monotonic

属性,values的值是否单调递增,返回boolean。

In [22]: pd.Series([1, 3, 5, 7, 7]).is_monotonic                                
Out[22]: True

In [24]: pd.Series([1, 3, 5, 7, 7, 6]).is_monotonic                             
Out[24]: False

17. Series.is_monotonic_increasing

Series.is_monotonic_increasing

属性,同is_monotonic。

18. Series.is_monotonic_decreasing

Series.is_monotonic_decreasing

属性,values的值是否单调递减,返回boolean。

In [26]: pd.Series(['d', 'c', 'b', 'a']).is_monotonic_decreasing                
Out[26]: True

In [27]: pd.Series(['d', 'c', 'b', 'a', 'f']).is_monotonic_decreasing           
Out[27]: False

19. Series.value_counts()

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

返回一个包含唯一值计数的Series。生成的对象将按降序排列,以便第一个元素是最频繁出现的元素。默认情况下不包括NA值。

常用参数介绍:
In [28]: index = pd.Index([3, 1, 2, 3, 4, np.nan]) 
    ...: index.value_counts()                                                   
Out[28]: 
3.0    2
4.0    1
2.0    1
1.0    1
dtype: int64

# 将normalize设置为True时,通过将所有值除以值的总和来返回相对频率
In [29]: s = pd.Series([3, 1, 2, 3, 4, np.nan]) 
    ...: s.value_counts(normalize=True)                                         
Out[29]: 
3.0    0.4
4.0    0.2
2.0    0.2
1.0    0.2
dtype: float64

# bins参数 分成3组
In [30]: s.value_counts(bins=3)                                                 
Out[30]: 
(2.0, 3.0]      2
(0.996, 2.0]    2
(3.0, 4.0]      1
dtype: int64

# 将dropna设置为False,我们还可以看到NaN索引值
In [31]: s.value_counts(dropna=False)                                           
Out[31]: 
3.0    2
NaN    1
4.0    1
2.0    1
1.0    1
dtype: int64
上一篇下一篇

猜你喜欢

热点阅读