數值計算與統計
對於DataFrame來說,求和、最大、最小、平均等統計方法,默認是按列進行統計,即axis = 0,如果添加參數axis = 1則會按照行進行統計。
如果存在空值,在統計時默認會忽略空值,如果添加參數skipna = False,統計時不會忽略空值。
- round(n) 保留n個小數
- count() 非NaN的元素個數
- sum() 和
- mean() 平均值
- median() 中位數
- max() 最大值
- min() 最小值
- mode()眾數
- std() 標准差
- var() 方差
- describe():包括count()、mean()、std()、min()、25%、50%、75%、max()
- skew(),樣本的偏度
- kurt(),樣本的峰度
分位數
quantile(q=0.5,axis=0),統計分位數,q確定位置,默認為0.5,axix=0默認按行統計,1按列統計 【適用於Seris和DataFrame】
計算邏輯:r = i + ( j - i ) * f
①將行或者列按數值大小升序排序,並計算位置pos = 1+(n-1)*q,其中n為行或列的長度,q為定義的參數
②根據pos確定 i 和 j,例如計算得pos=3.2,則i為第3個數,j為第4個數,f為pos的小數部分

dic = {'one':[1,3,2,5,4],'two':[2,4,3,6,5],'three':[3,7,5,6,4]} df = pd.DataFrame(dic,index=list('abcde')) print(df) print(df.quantile(0.1)) print(df.quantile([0.5,0.7])) # one two three # a 1 2 3 # b 3 4 7 # c 2 3 5 # d 5 6 6 # e 4 5 4 # one 1.4 # two 2.4 # three 3.4 # Name: 0.1, dtype: float64 # one two three # 0.5 3.0 4.0 5.0 # 0.7 3.8 4.8 5.8
以上以quantile(q=0.7)為例講解,按照列進行統計,每列的長度為5
pos = 1 + ( 5 - 1 ) * 0.7 = 3.8,因此i為每列的第3位數,j為每列的第4位數,且f為3.8的小數部分即0.8
result_one = 3 + ( 4 - 3 ) * 0.8 = 3.8
result_two = 4 + ( 5 - 4 ) * 0.8 = 4.8
reslut_three = 5+ ( 6 - 5 ) * 0.8 = 5.8
上四分位和下四分位確定位置pos = (n-1)/4和pos=3* (n-1)/4,結果計算同為r = i + ( j - i ) * f
四分位參考https://blog.csdn.net/kevinelstri/article/details/52937236
累計值
cumsum() 累計和、cumprod() 累計積、cummax()累計最大值、cummin()累計最小值【適用於Seris和DataFrame】

dic = {'one':[1,3,2,5,4],'two':[2,4,3,6,5]} df = pd.DataFrame(dic,index=list('abcde')) df['one_cumsum'] = df['one'].cumsum() #相當於增加一列 df['one_cumprod'] = df['one'].cumprod() df['two_cummax'] = df['two'].cummax() df['two_cummin'] = df['two'].cummin() print(df) # one two one_cumsum one_cumprod two_cummax two_cummin # a 1 2 1 1 2 2 # b 3 4 4 3 4 2 # c 2 3 6 6 4 2 # d 5 6 11 30 6 2 # e 4 5 15 120 6 2
唯一值
對序列進行唯一值unique()之后生成的是一維數組 【適用於Seris】

s = pd.Series(list('abaefb')) print(s) sq = s.unique() print(sq,type(sq)) sq_s = pd.Series(sq) # 0 a # 1 b # 2 a # 3 e # 4 f # 5 b # dtype: object # ['a' 'b' 'e' 'f'] <class 'numpy.ndarray'>
值計數
value_counts(),統計Seris中相同的值出現的次數,生成一個新的Seris,新Seris的index為原來的值,值為出現的次數 【適用於Seris】
參數:normalize=False, sort=True, ascending=False,bins=None, dropna=True,即默認會將結果倒序排序

s = pd.Series(list('abaefb')) s_count = s.value_counts() print(s) print(s_count,type(s_count)) # 0 a # 1 b # 2 a # 3 e # 4 f # 5 b # dtype: object # a 2 # b 2 # f 1 # e 1 # dtype: int64 <class 'pandas.core.series.Series'>
成員判斷
isin([ ]),成員要使用中括號括起來,判斷每個元素是否在中括號的元素中,生成的結果為布爾型的Seris或DataFrame 【適用於Seris和DataFrame】

# s = pd.Series(list('abced')) # df = pd.DataFrame(np.arange(6).reshape(2,3),columns=['a','b','c']) # print(s.isin(['a','b'])) # print(df.isin([1,2])) # 0 True # 1 True # 2 False # 3 False # 4 False # dtype: bool # a b c # 0 False True True # 1 False False False