九、累計與分組
1.獲取數據
本節用一份Seaborn 程序庫行星數據來進行演示(planets)
2.Pandas的簡單累計功能
df.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
describe() 方法可以計算每一列的若干常用統計值
Pandas的累計方法
指標 | 描述 |
---|---|
count() | 計數項 |
first()、 last() | 第一項與最後 |
mean()、 median() | 均值與中位數 |
min()、 max() | 最小值與最大 |
std()、 var() | 標準差與方差 |
mad() | 均值絕對偏差 |
prod() | 所有項乘積 |
sum() | 所有項求和 |
3.GroupBy: 分割splite、 應用apply和組合combine
df.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)
1)分割、應用和組合
GroupBy 的用處就是將這些分割、應用和組合步驟進行抽象:用戶不需要知道在底層如何計算,只要把操作看成一個整體就夠了.
返回的是一個 DataFrameGroupBy 對象,是一種特殊形式的 DataFrame,裏面隱藏着若干組數據,但是在沒有應用累計函數之前不會計算
2)GroupBy對象
GroupBy 對象是一種非常靈活的抽象類型,可以將它看成是 DataFrame的集合,在底層解決所有難題
(1)、按列取值
df.info()可以查看DataFrame數據類型
從原來的 DataFrame 中取某個列名作爲一個 Series 組。與 GroupBy 對象一樣,直到我們運行累計函數,纔會開始計算
(2)、按組迭代
GroupBy 對象支持直接按組進行迭代,返回的每一組都是 Series 或 DataFram
(3)、 調用方法
3)累計aggregate()、 過濾filter()、 轉換transform()和應用apply()
(1)、累計aggregate()/agg()
df.aggregate(func, axis=0, *args, **kwargs)
aggregate() 比起sum() 和 median() 之類的簡單函數可以支持更復雜的操作,比如字符串、函數或者函數列表,並且能一次性計算所有累計值
縮寫agg()
參數func:function, string, dictionary, or list of string/functions
- string function name.
- function.
- list of functions.
- dict of column names -> functions (or list of functions).
另一種用法就是通過 Python 字典指定不同列需要累計的函數
對應SQL
(2)、過濾filter()
過濾操作可以讓你按照分組的屬性丟棄若干數據。
df.filter(items=None, like=None, regex=None, axis=None)
傳入df輸出df,
分組求完std值後跟4比較,不滿足>4要求的只有A組,因此在原DF中剔除A組的數據,返回的是原DF篩選結果後的數據,不是分組後的DataFrameGroupBy
SQL類似(但SQL中求標準差結果異常)
filter() 函數會返回一個布爾值,表示每個組是否通過過濾
(3)、轉換transform()
df.transform(func, *args, **kwargs)
累計操作返回的是對組內全量數據縮減過的結果,而轉換操作會返回一個新的全
量數據。數據經過轉換之後,其形狀與原來的輸入數據是一樣的。
傳入df輸出df
對應SQL
(4) apply() 方法
- 基礎的應用函數
- 分組中的apply
對應SQL
4)設置分割的鍵
by : mapping, function, label, or list of labels
Used to determine the groups for the groupby.
Ifby
is a function, it’s called on each value of the object’s
index. If a dict or Series is passed, the Series or dict VALUES
will be used to determine the groups (the Series’ values are first
aligned; see.align()
method). If an ndarray is passed, the
values are used as-is determine the groups. A label or list of
labels may be passed to group by the columns inself
. Notice
that a tuple is interpreted a (single) key.
(1)將列表、數組、Series或索引作爲分組建
df外重新定義分組依據
(2)用字典或 Series 將索引映射到分組名稱
df.set_index()將列轉化成索引
借用原索引,設置映射,重新分組
(3)任意 Python 函數
(4) 多個有效鍵構成的列表(多重分組)
任意之前有效的鍵都可以組合成一個列表,進行分組,從而返回一個多級索引的分組結果
5)分組案例
series.astype()轉換數據類型
series.unstack() 方法可以快速將一個多級索引的Series 轉化爲普通索引的 DataFrame
df.T可以轉置