1、pandas層級索引
pandas的層級索引對象就是MulitIndex。設置多個索引列需要使用set_index()方法,當要多層級索引進行排序時需要使用sort_index()方法。
【set_index()】
def set_index(self, keys, drop=True, append=False, inplace=False,
verify_integrity=False):
對源碼中set_index()參數說明
(1)drop參數:刪除要作用的索引列
(2)append參數:向現有追加索引列
設置多個索引列使用set_index( ['外層索引','內層索引'],inplace=True) 方法;參數inplace爲True表示直接修改DataFrame對象無法返回值。
【選取子集】
(1)取外層索引就是:loc['outer_index'],就是set_index()方法寫在前面的索引;
(2)取內層索引:loc['outer_index','inner_index'];取內層索引必須先寫外層索引。
【sort_index()方法】
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
kind='quicksort', na_position='last', sort_remaining=True,
by=None)
通過上面的源碼我們發現sort_index()方法的level參數默認值爲None,但是需要我們注意的level值跟我們設置set_index()方法設置的多個索引列的個數一致性,就是設置幾個索引列level參數就可以爲幾,只不過level是從0開始的。
import pandas as pd
# 文件路徑
filename = "./happiness.csv"
# usecols=[] 參數表示讀取指定列數據
data = pd.read_csv(filename,usecols=['Country', 'Region', 'Happiness Rank', 'Happiness Score'])
# 設置多個索引列,一般設置多個索引列時,這個列表中大分類在前面小分類在後面,否則設置無意義。
data.set_index(['Region', 'Country'],inplace=True) # inplace=True表示直接修改dataframe數據
# 外層選擇,也就是set_index()設置多個索引列的中最前面的一個索引
# print(data.loc['Western Europe']) # 結果是dataframe對象
print("="*90)
# 內層選取
# print(data.loc['Australia and New Zealand', 'New Zealand']) # 結果是Series對象
# swaplevel()方法交換層級,就是交換內外層進行交換。
print(data.swaplevel())
# 層級索引排序;我們在set_index()中設置幾個索引列,這裏的level就可以設置值就是對應的個數,只是level從0開始,0表示最外層索引列
print(data.sort_index(level=0).head(10)) # level默認值爲None
2、分組和聚合
分組:對數據集體進行分組,然後對每組進行統計分析。pandas利用groupby()方法進行更加複雜的分組運算。分組的運算過程一般是split--->apply--->combine。
(1)拆分:進行分組的根據;
(2)應用:每個分組運算的計算規則;
(3)合併:把每個分組的計算結果合併。
聚合:數組產生標量的過程,如mean()/count()等。常用於分組後的數據進行計算;內置的聚合函數有sum()/max()/min()等。
2.1、分組操作
【按單列分組】使用DataFrame對象的groupby(''label")。
【按多列分組】使用DataFrame對象的groupby( ["label1", "label2"] )--->多層dataframe。
我們需要注意的是在使用groupby()方法操作後產生的是一個GroupBy對象;DataFrameGroupBy或者SeriesGroupBy。GroupBy對象沒有進行實際的運算,只是包含分組的中間數據。
【對GroupBy對象進行分組聚合操作】
(1)常用的聚合操作:mean()/sum()/size()/min()/count()。
(2)非數值數據不進行分組運算。
2.2、聚合操作