Pandas基础3.2|Python学习笔记

import numpy as np
import pandas as pd
df = pd.read_csv('./data/table.csv',index_col = 'ID')
df.head()
Unnamed: 0SchoolClassGenderAddressHeightWeightMathPhysics
ID
11010S_1C_1Mstreet_11736334.0A+
11021S_1C_1Fstreet_21927332.5B+
11032S_1C_1Mstreet_21868287.2B+
11043S_1C_1Fstreet_21678180.4B-
11054S_1C_1Fstreet_41596484.8B+

聚合、过滤和变换

聚合(Aggregation)

常用聚合函数
  • 聚合:将一系列数变成一个标量。e.g. mean/sum/size/count/std/var/sem/describe/first/last/nth/min/max
#验证标准误sem函数
grouped_single = df.groupby('School')
group_m = grouped_single['Math']
group_m.std().values/np.sqrt(group_m.count().values)==group_m.sem().values
array([ True,  True])
同时使用多个聚合函数
group_m.agg(['sum','mean','std'])
summeanstd
School
S_1956.263.74666723.077474
S_21191.159.55500017.589305
利用元组进行重命名
group_m.agg([('rename_sum','sum'),('rename_mean','mean'),('rename_std','std')])
rename_sumrename_meanrename_std
School
S_1956.263.74666723.077474
S_21191.159.55500017.589305
指定哪些函数作用哪些列
grouped_mul = df.groupby(['School','Class'])
grouped_mul.agg({'Math':['mean','max'],'Height':'var'})
MathHeight
meanmaxvar
SchoolClass
S_1C_163.7887.2183.3
C_264.3097.0132.8
C_363.1687.7179.2
S_2C_158.5683.354.7
C_262.8085.4256.0
C_363.0695.5205.7
C_453.8067.7300.2
自定义函数
grouped_single['Math'].agg(lambda x:print(x.head(),'间隔'))
#agg函数一个有用的特性:分组逐列进行agg函数的传入
1101    34.0
1102    32.5
1103    87.2
1104    80.4
1105    84.8
Name: Math, dtype: float64 间隔
2101    83.3
2102    50.6
2103    52.5
2104    72.2
2105    34.2
Name: Math, dtype: float64 间隔





School
S_1    None
S_2    None
Name: Math, dtype: object
  • RMK:官方没有提供计算极差的函数,可以用agg实现组内极差计算
grouped_single['Math'].agg(lambda x: x.max()-x.min())
School
S_1    65.5
S_2    62.8
Name: Math, dtype: float64
利用NamedAgg函数进行多个聚合
  • RMK:不支持lambda函数,但是可以使用外置的def函数
def R1(x):
    return x.max()-x.min()
def R2(x):
    return x.max()-x.median()
grouped_single['Math'].agg(min_score1=pd.NamedAgg(column='col1',aggfunc=R1),max_score1=pd.NamedAgg(column='col2',aggfunc='max'),range_score2=pd.NamedAgg(column='col3',aggfunc=R2)).head()
min_score1max_score1range_score2
School
S_165.597.033.5
S_262.895.539.4
带参数的聚合函数
#判断是否组内数学分数至少有一个值在50-52之间
def f(s,low,high):
    return s.between(low,high).max()
grouped_single['Math'].agg(f,50,52)
School
S_1    False
S_2     True
Name: Math, dtype: bool
如果需要使用多个函数,并且其中至少有一个带参数,则使用wrap技巧
def f_test (s,low,high):
    return s.between(low,high).max()
def agg_f(f_mul,name,*args,**kwargs):
    def wrapper(x):
        return f_mul(x,*args,**kwargs)
    wrapper.__name__=name
    return wrapper
new_f = agg_f(f_test,'at_least_one_in_50_52',50,52)
grouped_single['Math'].agg([new_f,'mean']).head()
at_least_one_in_50_52mean
School
S_1False63.746667
S_2True59.555000

过滤(Filteration)

  • filter函数:用来筛选某些组(结果为组的全体),故传入的值是布尔标量
grouped_single[['Math','Physics']].filter(lambda x: (x['Math']>30).all()).head()
MathPhysics
ID
110134.0A+
110232.5B+
110387.2B+
110480.4B-
110584.8B+

变换(Transformation)

传入对象
  • Transform函数中出传入的对象是组内的列,并且返回值需要与列长完全一致
grouped_single[['Math','Height']].transform(lambda x : x-x.min()).head()
MathHeight
ID
11012.514
11021.033
110355.727
110448.98
110553.30
  • 若返回了标量值,则组内的所有元素都会被广播为这个值
grouped_single[['Math','Height']].transform(lambda x:x.mean()).head()
MathHeight
ID
110163.746667175.733333
110263.746667175.733333
110363.746667175.733333
110463.746667175.733333
110563.746667175.733333
利用变换方法进行组内标准化
grouped_single[['Math','Height']].transform(lambda x:(x-x.mean())/x.std()).head()
MathHeight
ID
1101-1.288991-0.214991
1102-1.3539901.279460
11031.0162870.807528
11040.721627-0.686923
11050.912289-1.316166
利用变换方法进行组内缺失值的均值填充
df_nan_1 = df[['Math','School']].copy()
df_nan_1.head()
MathSchool
ID
110134.0S_1
110232.5S_1
110387.2S_1
110480.4S_1
110584.8S_1
df_nan = df_nan_1.reset_index()
df_nan.loc[np.random.randint(0,df.shape[0],25),['Math']] = np.nan
df_nan.head()
IDMathSchool
01101NaNS_1
11102NaNS_1
2110387.2S_1
31104NaNS_1
41105NaNS_1
df_nan.groupby('School').transform(lambda x:x.fillna(x.mean())).join(df.reset_index()['School']).head()
IDMathSchool
0110183.225S_1
1110283.225S_1
2110387.200S_1
3110483.225S_1
4110583.225S_1

apply函数

apply函数的灵活性

  • 所有分组函数中,apply应用最为广泛
#对于传入值而言,从下面的打印内容可看出是以分组的表传入apply中
df.groupby('School').apply(lambda x:print(x.head(1)))
      Unnamed: 0 School Class Gender   Address  Height  Weight  Math Physics
ID                                                                          
1101           0    S_1   C_1      M  street_1     173      63  34.0      A+
      Unnamed: 0 School Class Gender   Address  Height  Weight  Math Physics
ID                                                                          
2101          15    S_2   C_1      M  street_7     174      84  83.3       C
apply函数的灵活性很大程度上来源于其返回值的多样性
  1. 标量返回值
df[['School','Math','Height']].groupby('School').apply(lambda x:x.max())
SchoolMathHeight
School
S_1S_197.0195
S_2S_295.5194
  1. 列表返回值
df[['School','Math','Height']].groupby('School').apply(lambda x: x- x.min()).head()
MathHeight
ID
11012.514.0
11021.033.0
110355.727.0
110448.98.0
110553.30.0
  1. 数据框返回值
df[['School','Math','Height']].groupby('School').apply(lambda x:pd.DataFrame({'col1':x['Math']-x['Math'].max()})).head()
col1
ID
1101-63.0
1102-64.5
1103-9.8
1104-16.6
1105-12.2

用apply同时统计多个指标

  • 可借助OrderedDict工具进行快捷统计
from collections import OrderedDict
def f(df):
    data = OrderedDict()
    data['M_sum'] = df['Math'].sum()
    data['W_var'] = df['Weight'].var()
    data['H_mean'] = df['Height'].mean()
    return pd.Series(data)
grouped_single.apply(f)
M_sumW_varH_mean
School
S_1956.2117.428571175.733333
S_21191.1181.081579172.950000
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值