暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python数据分析笔记#7.2.7 排列和随机采样

Yuan的学习笔记 2022-01-12
543



「目录」

数据清洗和准备

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进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论