「目录」
数据清洗和准备
Data Cleaning and Prepration
7.1 => 处理缺失数据
7.2 => 数据转换
--------> 移除重复数据
--------> 利⽤函数或映射进行数据转换
--------> 替换值
--------> 重命名轴索引
--------> 离散化和面元划分
--------> 检测和过滤异常值
--------> 排列和随机采样
7.3 => 字符串操作
排列和随机采样
今天这篇笔记呢更新原书排列和随机采样的部分,涉及到了以下几个函数:
numpy.random.permutation() DataFrame.take() DataFrame.sample()
利用numpy.random.permutation函数可以轻松实现对Series或DataFrame的行rows进行排列。
通过调用permutation并传入axis轴的长度,会产生一组表示新顺序的整数数组:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame(np.arange(5*4).reshape((5,4)))
In [4]: sampler = np.random.permutation(5)
In [5]: sampler
Out[5]: array([3, 4, 2, 1, 0])复制
然后可以在take函数中使用该数组。
In [6]: df
Out[6]:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
In [7]: df.take(sampler)
Out[7]:
0 1 2 3
3 12 13 14 15
4 16 17 18 19
2 8 9 10 11
1 4 5 6 7
0 0 1 2 3复制
原书没有多讲几句关于take函数的作用,稍微补充一下哈。
take函数会沿轴返回给定位置的元素,注意是给定位置哦。
In [17]: data = pd.DataFrame(np.arange(6*4).reshape((6, 4)), index=['One', 'Two', 'Three', 'Four', 'Five', 'Six'], columns=['A', 'B', 'C', 'D'])
In [18]: data
Out[18]:
A B C D
One 0 1 2 3
Two 4 5 6 7
Three 8 9 10 11
Four 12 13 14 15
Five 16 17 18 19
Six 20 21 22 23
#选取第0,2,4行
In [19]: data.take([0, 2, 4])
Out[19]:
A B C D
One 0 1 2 3
Three 8 9 10 11
Five 16 17 18 19
#选取第0,3列
In [21]: data.take([0,3], axis=1)
Out[21]:
A D
One 0 3
Two 4 7
Three 8 11
Four 12 15
Five 16 19
Six 20 23复制
在DataFrame上使用sample方法可以选取随机子集:
In [8]: df.sample(n=3)
Out[8]:
0 1 2 3
3 12 13 14 15
0 0 1 2 3
1 4 5 6 7复制
记得概率课上的摸球实验吗,现在假如有5个球,编号分别为5,7,-1,6,4,现在传入n=10表示摸10次,replace=True代表可以重复选择(摸完后放回):
In [9]: choices = pd.Series([5, 7, -1, 6, 4])
In [10]: draws = choices.sample(n=10, replace=True)
In [11]: draws
Out[11]:
0 5
2 -1
3 6
4 4
2 -1
0 5
3 6
1 7
0 5
1 7
dtype: int64复制
这么解释很形象吧。
这篇结束了,BYE-BYE,下篇见吧。

往期回顾



Stay hungry, stay foolish
文章转载自Yuan的学习笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
[MYSQL] 服务器出现大量的TIME_WAIT, 每天凌晨就清零了
大大刺猬
143次阅读
2025-04-01 16:20:44
mysql提升10倍count(*)的神器
大大刺猬
123次阅读
2025-03-21 16:54:21
演讲实录|分布式 Python 计算服务 MaxFrame 介绍及场景应用方案
阿里云大数据AI技术
121次阅读
2025-03-17 13:27:37
官宣,Milvus SDK v2发布!原生异步接口、支持MCP、性能提升
ZILLIZ
96次阅读
2025-04-02 09:34:13
[MYSQL] query_id和STATEMENT_ID在不同OS上的关系
大大刺猬
64次阅读
2025-03-26 19:08:13
DataWorks :Data+AI 一体化开发实战图谱
阿里云大数据AI技术
46次阅读
2025-03-19 11:00:55
国密算法介绍
漫步者
44次阅读
2025-03-21 09:20:39
如何使用 RisingWave 和 PuppyGraph 构建高性能实时图分析框架
RisingWave中文开源社区
37次阅读
2025-03-18 10:49:54
WingPro for Mac 强大的Python开发工具 v10.0.9注册激活版
一梦江湖远
33次阅读
2025-03-29 10:33:27
python操作MySQL数据库
怀念和想念
29次阅读
2025-03-30 23:22:07