对Python random模块打乱数组顺序的实例讲解
作者:落叶_小唱 时间:2023-03-24 16:51:57
在我们使用一些数据的过程中,我们想要打乱数组内数据的顺序但不改变数据本身,可以通过改变索引值来实现,也就是将索引值重新随机排列,然后生成新的数组。功能主要由python中random模块的sample()函数实现。
sample(population, k) method of random.Random instance
Chooses k unique random elements from a population sequence or set.
下面的代码实现的是打乱iris数据,iris数据是网上下载的csv格式文件,相信大家不陌生的了,原始数据是三种鸢尾(iris)顺序排列的,三种花分别是:setosa,versicolor 和 virginica ,记录的数据有SepalLengthCm(花萼长度), SepalWidthCm(花萼宽度), PetalLengthCm(花瓣长度), PetalWidthCm (花瓣宽度)
在做聚类分析的时候曾经用到过iris数据,当然,如果安装了scikit learn 模块的话,可以通过
from sklearn import datasets
iris = datasets.load_iris()
获取
参考链接:http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
下面的程序实现打乱iris的数据顺序:
import pandas as pd
import random as rd # 导入random模块,使用里面的sample函数
from pylab import *
iris = pd.read_csv('D:\\Iris.csv')
a1=reshape(iris['Id'],[150,1])
a2=reshape(iris['SepalLengthCm'],[150,1])
a3=reshape(iris['SepalWidthCm'],[150,1])
data=c_[a1,a2,a3]
idx=rd.sample(range(150),150)
iris = data[idx] # 打乱顺序,这里只选取了花萼长度和宽度这两个特征值
2017/7/10 updated
打乱顺序的方法还可以使用random.shuffle(iterable),这样会直接改变iterable的顺序,shuffle 是洗牌的意思,顾名思义,需要注意的是random.shufle()函数没有返回值,如果写成
mylist = random.shuffle(list1)
将不会得到任何结果
来源:https://blog.csdn.net/ouening/article/details/55254984
标签:Python,random
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python偏函数Partial function使用方法实例详解
2023-02-07 09:47:02
给Django Admin添加验证码和多次登录尝试限制的实现
2022-10-17 01:09:34
![](https://img.aspxhome.com/file/2023/0/133220_0s.png)
使用setup.py安装python包和卸载python包的方法
2023-01-31 02:20:47
mysql慢查询日志轮转_MySQL慢查询日志实操
2024-01-26 05:54:14
![](https://img.aspxhome.com/file/2023/5/69775_0s.png)
python next()和iter()函数原理解析
2023-04-05 21:58:50
Python面向对象程序设计类变量与成员变量、类方法与成员方法用法分析
2022-08-11 15:43:43
python获取全国城市pm2.5、臭氧等空气质量过程解析
2023-06-04 21:46:07
单利模式及python实现方式详解
2021-07-21 21:45:15
python3中编码获取网页的实例方法
2023-07-17 23:31:47
![](https://img.aspxhome.com/file/2023/1/75931_0s.png)
教你使用SQL Server数据库进行网络链接
2009-01-13 13:41:00
解析mysql 5.5字符集问题
2024-01-13 09:01:54
简单谈谈python中的多进程
2023-05-13 15:19:17
Vue中使用和移除总线Bus的注意事项详解
2024-06-05 15:30:33
![](https://img.aspxhome.com/file/2023/5/123135_0s.jpg)
使用一条INSERT语句完成多表插入
2010-03-18 11:08:00
解析Python中的eval()、exec()及其相关函数
2023-12-16 02:51:59
python实现雪花飘落效果实例讲解
2022-08-29 07:31:55
![](https://img.aspxhome.com/file/2023/7/110397_0s.png)
解决Pandas的DataFrame输出截断和省略的问题
2021-10-28 10:22:19
![](https://img.aspxhome.com/file/2023/5/76815_0s.jpg)
python实现从pdf文件中提取文本,并自动翻译的方法
2021-06-08 18:55:56
![](https://img.aspxhome.com/file/2023/5/84135_0s.jpg)
python 机器学习之支持向量机非线性回归SVR模型
2022-06-17 20:23:55
![](https://img.aspxhome.com/file/2023/1/75941_0s.png)
Vue实现无限加载瀑布流
2024-05-09 15:23:16
![](https://img.aspxhome.com/file/2023/1/126431_0s.gif)