常用的主要是4个:
n默认为5
df.describe() #运行截图 Height Weight count 183.000000 189.000000 mean 163.218033 55.015873 std 8.608879 12.824294 min 145.400000 34.000000 25% 157.150000 46.000000 50% 161.900000 51.000000 75% 167.500000 65.000000 max 193.900000 89.000000
在Series和DataFrame上定义了许多统计函数,最常见的是:
用法示例
df_demo = df[['Height', 'Weight']] df_demo.mean()
聚合函数
聚合函数,有一个公共参数axis,axis=0代表逐列聚合,axis=1表示逐行聚合
df_demo.mean(axis=1).head()
唯一值函数常用的四个函数:
drop_duplicates()基本用法
需要指定列
代码:
#原本的数据样例 df_demo = df[['Gender','Transfer','Name']] df_demo
Gender Transfer Name 0 Female N Gaopeng Yang 1 Male N Changqiang You 2 Male N Mei Sun 3 Female N Xiaojuan Sun 4 Male N Gaojuan You ... ... ... ... 195 Female N Xiaojuan Sun 196 Female N Li Zhao 197 Female N Chengqiang Chu 198 Male N Chengmei Shen 199 Male N Chunpeng Lv 200 rows × 3 columns
#现给Gender,Transfer两列去重 df_demo.drop_duplicates(['Gender','Transfer'])
Gender Transfer Name 0 Female N Gaopeng Yang 1 Male N Changqiang You 12 Female NaN Peng You 21 Male NaN Xiaopeng Shen 36 Male Y Xiaojuan Qin 43 Female Y Gaoli Feng
由此可见,使用了first参数,保留第一次出现的重复行,删除后面的重复行
在未指定参数的情况下,keep默认first;
指定last
案例如下:
df_demo.drop_duplicates(['Gender', 'Transfer'], keep='last')
Gender Transfer Name 147 Male NaN Juan You 150 Male Y Chengpeng You 169 Female Y Chengquan Qin 194 Female NaN Yanmei Qian 197 Female N Chengqiang Chu 199 Male N Chunpeng Lv
last:删除所有的重复行,只保留出现的最后一个
drop_duplicates() & duplicated()的区别
duplicated和drop_duplicates的功能类似,但前者返回了是否为唯一值的布尔列表,其keep参数与后者一致。其返回的序列,把重复元素设为True,否则为False。 drop_duplicates等价于把duplicated为True的对应行剔除。
替换函数有三类:
replace的用法
#原本的数据 df_demo = df[['Gender','Transfer','Name']] df_demo
Gender Transfer Name 0 Female N Gaopeng Yang 1 Male N Changqiang You 2 Male N Mei Sun 3 Female N Xiaojuan Sun 4 Male N Gaojuan You ... ... ... ... 195 Female N Xiaojuan Sun 196 Female N Li Zhao 197 Female N Chengqiang Chu 198 Male N Chengmei Shen 199 Male N Chunpeng Lv 200 rows × 3 columns
#替换Gender,女替换为0,男替换为1 df['Gender'].replace({'Female':0, 'Male':1}).head()
0 0 1 1 2 1 3 0 4 1 Name: Gender, dtype: int64
逻辑替换
逻辑替换包括了where和mask,这两个函数是完全对称的:where函数在传入条件为False的对应行进行替换,而mask在传入条件为True的对应行进行替换,当不指定替换值时,替换为缺失值(NAN)
s = pd.Series([-1, 1.2345, 100, -50]) s.where(s<0)
0 -1.0 1 NaN 2 NaN 3 -50.0 dtype: float64
s.where(s<0, 100)
0 -1.0 1 100.0 2 100.0 3 -50.0 dtype: float64
s.mask(s<0)
0 NaN 1 1.2345 2 100.0000 3 NaN dtype: float64
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理