30 個函數玩轉 Pandas 統計計算!
作者:才哥
大家好,我是才哥。
我在進行數據處理的時候除了清洗篩選處理外還會涉及到統計計算處理,這裏我們就來介紹一些常見的統計計算函數吧。
- 數據預覽
本文案例演示數據來自國家數據中心的各地區最近 5 年的國民生產總值數據,後臺回覆gdp
可以領取數據文件,方便自己試一試哈。
In [1]: df.head() # 預覽前5條數據
Out[1]:
地區 2020年 2019年 2018年 2017年 2016年
0 北京市 36102.6 35445.1 33106.0 29883.0 27041.2
1 天津市 14083.7 14055.5 13362.9 12450.6 11477.2
2 河北省 36206.9 34978.6 32494.6 30640.8 28474.1
3 山西省 17651.9 16961.6 15958.1 14484.3 11946.4
4 內蒙古自治區 17359.8 17212.5 16140.8 14898.1 13789.3
In [2]: df.info() # 查看各字段數據類型、條數及空值數
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 32 entries, 0 to 31
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 地區 32 non-null object
1 2020年 31 non-null float64
2 2019年 31 non-null float64
3 2018年 31 non-null float64
4 2017年 31 non-null float64
5 2016年 31 non-null float64
dtypes: float64(5), object(1)
memory usage: 1.6+ KB
- 描述統計
describe
函數方法 可以返回數據集的描述性統計
Signature:
df.describe(
percentiles=None,
include=None,
exclude=None,
datetime_is_numeric=False,
) -> 'FrameOrSeries'
Docstring:
Generate descriptive statistics.
對於Dataframe
類型來說,每行對應一個統計指標,分別是總數、平均值、標準差、最小值、四分位(默認是 25/50/75)和最大值。
In [3]: df.describe()
Out[3]:
2020年 2019年 2018年 2017年 2016年
count 31.000000 31.000000 31.000000 31.000000 31.000000
mean 32658.551613 31687.758065 29487.661290 26841.819355 24224.148387
std 26661.811640 25848.652250 24136.181387 22161.575235 20008.278500
min 1902.700000 1697.800000 1548.400000 1349.000000 1173.000000
25% 13940.650000 13826.300000 13104.700000 12381.800000 11634.800000
50% 25115.000000 24667.300000 22716.500000 20210.800000 18388.600000
75% 42612.500000 41110.350000 37508.750000 33835.250000 30370.250000
max 110760.900000 107986.900000 99945.200000 91648.700000 82163.200000
上面的描述性統計表,我們可以看到 2020 年一共有 31 個地區有數據,GDP 均值爲 3.26 萬億,最高的 11.07 萬億,最低的 0.19 萬億等。
我們可以看到,還有參數可以進行自定義選擇,作用如下:
percentiles
可以自定指定分位數
In [4]: df.describe(percentiles=[.2, .4, .6, .8])
Out[4]:
2020年 2019年 2018年 2017年 2016年
count 31.000000 31.000000 31.000000 31.000000 31.000000
mean 32658.551613 31687.758065 29487.661290 26841.819355 24224.148387
std 26661.811640 25848.652250 24136.181387 22161.575235 20008.278500
min 1902.700000 1697.800000 1548.400000 1349.000000 1173.000000
20% 13698.500000 13544.400000 12809.400000 11159.900000 10427.000000
40% 22156.700000 21237.100000 19627.800000 17790.700000 16116.600000
50% 25115.000000 24667.300000 22716.500000 20210.800000 18388.600000
60% 36102.600000 34978.600000 32494.600000 29676.200000 26307.700000
80% 43903.900000 45429.000000 42022.000000 37235.000000 33138.500000
max 110760.900000 107986.900000 99945.200000 91648.700000 82163.200000
include
,exclude
分別指定和排除數據類型,比如
df.describe(include=[np.number]) # 指定數字類型的字段
df.describe(exclude=[np.float]) # 排除浮點類型的字段
我們可以看到,默認情況下 describe 指定的都是數字類型的,地區字段部分的未參與,如果想參與可以通過include='all'
來指定。
In [5]: df.describe(include='all')
Out[5]:
地區 2020年 2019年 2018年 2017年 2016年
count 32 31.00 31.00 31.00 31.00 31.00
unique 32 NaN NaN NaN NaN NaN
top 北京市 NaN NaN NaN NaN NaN
freq 1 NaN NaN NaN NaN NaN
... ... ... ... ... ... ...
25% NaN 13940.65 13826.30 13104.70 12381.80 11634.80
50% NaN 25115.00 24667.30 22716.50 20210.80 18388.60
75% NaN 42612.50 41110.35 37508.75 33835.25 30370.25
max NaN 110760.90 107986.90 99945.20 91648.70 82163.20
[11 rows x 6 columns]
案例數據中,地區字段下的數據都是object
類型,非數字相關。我們可以發現在描述統計結果中,它新增了unique
、top
和frep
三個指標,相反這三個指標對於純數字類型的字段列是沒有的。這三個指標分別對應非重複數、最大值和頻率(如有重複的),比如下面這個單獨案例:
In [6]: s = pd.Series(['red','blue','black','grey','red','grey'])
In [7]: s.describe()
Out[7]:
count 6
unique 4
top red
freq 2
dtype: object
在descripe
函數中還有一個參數datetime_is_numeric
,如果是對時間類型數據的統計描述需要賦值True
。
In [8]: s = pd.Series([np.datetime64("2000-01-01"),
...: np.datetime64("2010-01-01"),
...: np.datetime64("2010-01-01")
...: ])
In [9]: s.describe()
FutureWarning: Treating datetime data as categorical rather than numeric in `.describe` is deprecated and will be removed in a future version of pandas. Specify `datetime_is_numeric=True` to silence this warning and adopt the future behavior now.
s.describe()
Out[9]:
count 3
unique 2
top 2010-01-01 00:00:00
freq 2
first 2000-01-01 00:00:00
last 2010-01-01 00:00:00
dtype: object
In [10]: s.describe(datetime_is_numeric=True)
Out[10]:
count 3
mean 2006-09-01 08:00:00
min 2000-01-01 00:00:00
25% 2004-12-31 12:00:00
50% 2010-01-01 00:00:00
75% 2010-01-01 00:00:00
max 2010-01-01 00:00:00
dtype: object
在我們日常數據處理中,除了描述統計裏的這些統計維度外,我們還會用到其他一些統計計算,比如方差、衆數等等。
- 統計計算
這裏我們演示常見的統計計算函數方法,默認情況下都是按列統計,我們也可以指定按行,具體見下方演示
# 最大值
In [11]: df.max(numeric_only=True)
Out[11]:
2020年 110760.9
2019年 107986.9
2018年 99945.2
2017年 91648.7
2016年 82163.2
dtype: float64
# 最小值
In [12]: df.min(numeric_only=True)
Out[12]:
2020年 1902.7
2019年 1697.8
2018年 1548.4
2017年 1349.0
2016年 1173.0
dtype: float64
# 平均值 (統計項的計算,建議指定數據類型爲僅數字,可以通過axis指定是行列,默認是列)
In [13]: df.mean(axis=1, numeric_only=True)
Out[13]:
0 32315.58
1 13085.98
2 32559.00
3 15400.46
...
28 2683.66
29 3432.18
30 12198.96
31 NaN
Length: 32, dtype: float64
以下部分不做具體演示,僅介紹函數功能,所有這些在使用的時候都要注意下原始數據類型,非數字類型可能會出現報錯
df.sum() # 求和
df.corr() # 相關係數
df.cov() # 協方差
df.count() # 非空計數
df.abs() # 絕對值
df.median() # 中位數
df.mode() # 衆數
df.std() # 標準差
df.var() # 無偏方差
df.sem() # 均值的標準誤差
df.mad() # 平均絕對差
df.prod() # 連乘
df.cumprod() # 累乘
df.cumsum() # 累加
df.nunique() # 非重複計數
df.idxmax() # 最大值索引名(注意是索引名,區別於argmax)
df.idxmin() # 最小值索引名
df.sample(5) # 隨機抽樣5條數據
df.skew() # 樣本偏度(第三階)
df.kurt() # 樣本偏度(第四階)
df.quantile() # 樣本分位數
df.rank() # 排名
df.pct_change() # 變化率
df.value_counts() # 不重複值及數量
s.argmax() # 最大值索引(自動索引),dataframe沒有
s.argmin() # 最小值索引(自動索引),dataframe沒有
其實,在每個函數中都有別的參數可以讓函數功能更強大,具體大家可以自行嘗試哈,我們這裏簡單舉個別例子。
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2) # 隔2行求變化率(默認是隔1行)
0 NaN
1 NaN
2 -0.055556
dtype: float64
除了上述這些函數外,以下幾個函數我們也常用到
# 某列最大的前5行數據
In [14]: df.nlargest(5,columns='2020年')
Out[14]:
地區 2020年 2019年 2018年 2017年 2016年
18 廣東省 110760.9 107986.9 99945.2 91648.7 82163.2
9 江蘇省 102719.0 98656.8 93207.6 85869.8 77350.9
14 山東省 73129.0 70540.5 66648.9 63012.1 58762.5
10 浙江省 64613.3 62462.0 58002.8 52403.1 47254.0
15 河南省 54997.1 53717.8 49935.9 44824.9 40249.3
# 某列最小的前五行數據
In [15]: df.nsmallest(5,columns='2020年')
Out[15]:
地區 2020年 2019年 2018年 2017年 2016年
25 西藏自治區 1902.7 1697.8 1548.4 1349.0 1173.0
28 青海省 3005.9 2941.1 2748.0 2465.1 2258.2
29 寧夏回族自治區 3920.5 3748.5 3510.2 3200.3 2781.4
20 海南省 5532.4 5330.8 4910.7 4497.5 4090.2
27 甘肅省 9016.7 8718.3 8104.1 7336.7 6907.9
加減乘除四則運算等
可以用運算符號,也可以用函數方法;同樣可以傳一個值,也可以傳一個DataFrame
或Serice
。
'''
Among flexible wrappers
(`add`, `sub`, `mul`, `div`, `mod`, `pow`)
to arithmetic
operators:
`+`, `-`, `*`, `/`, `//`, `%`, `**`.
'''
df + 1
df.add(1)
以上就是本次全部內容,感興趣的小夥伴可以自己跑一跑代碼試試,或者添加作者微信一起交流哦!
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/hd1ndYhjsaggMVU87YYB7Q