Datawhale 第十九期 Numpy下 之 Task05:实践大作业

本篇博客通过Numpy对鸢尾花数据集进行了深入的分析实践,包括数据导入、统计计算、数据清洗、相关性分析等,并展示了如何进行数据标准化、缺失值处理、分类变量创建等操作。

Datawhale 第十九期 Numpy下 之 Task05:实践大作业


本次练习使用 鸢尾属植物数据集 .\iris.data ,在这个数据集中,包括了三类不同的鸢尾属植物:
Iris Setosa,Iris Versicolour,Iris Virginica。每类收集了50个样本,因此这个数据集一共包含了
150个样本。

sepallength:萼片长度
sepalwidth:萼片宽度
petallength:花瓣长度
petalwidth:花瓣宽度

以上四个特征的单位都是厘米(cm)。

1. 导入鸢尾属植物数据集,保持文本不变。

import numpy as np
outfile = r'.\iris.data'
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris‐setosa']
# ['4.9' '3.0' '1.4' '0.2' 'Iris‐setosa']
# ['4.7' '3.2' '1.3' '0.2' 'Iris‐setosa']
# ['4.6' '3.1' '1.5' '0.2' 'Iris‐setosa']
# ['5.0' '3.6' '1.4' '0.2' 'Iris‐setosa']
# ['5.4' '3.9' '1.7' '0.4' 'Iris‐setosa']
# ['4.6' '3.4' '1.4' '0.3' 'Iris‐setosa']
# ['5.0' '3.4' '1.5' '0.2' 'Iris‐setosa']
# ['4.4' '2.9' '1.4' '0.2' 'Iris‐setosa']
# ['4.9' '3.1' '1.5' '0.1' 'Iris‐setosa']]

2. 求出鸢尾属植物萼片长度的平均值、中位数和标准差(第1列,sepallength)

import numpy as np
outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])
print(sepalLength[0:10])
# [5.1 4.9 4.7 4.6 5. 5.4 4.6 5. 4.4 4.9]
print(np.mean(sepalLength))
# 5.843333333333334
print(np.median(sepalLength))
# 5.8print(np.std(sepalLength))
# 0.8253012917851409

3. 创建一种标准化形式的鸢尾属植物萼片长度,其值正好介于0和1之间,这样最小值为0,最大值为1(第1列,sepallength)。

import numpy as np
outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])
# 方法1
aMax = np.amax(sepalLength)
aMin = np.amin(sepalLength)
x = (sepalLength ‐ aMin) / (aMax ‐ aMin)
print(x[0:10])
# [0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556
# 0.08333333 0.19444444 0.02777778 0.16666667]
# 方法2
x = (sepalLength ‐ aMin) / np.ptp(sepalLength)
print(x[0:10])
# [0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556
# 0.08333333 0.19444444 0.02777778 0.16666667]

4. 找到鸢尾属植物萼片长度的第5和第95百分位数(第1列,sepallength)。

import numpy as np
outfile = r'.\iris.data'
sepalLength = np.loadtxt(outfile, dtype=float, delimiter=',', skiprows=1, usecols=[0])
x = np.percentile(sepalLength, [5, 95])
print(x) # [4.6 7.255]

5. 把iris_data数据集中的20个随机位置修改为np.nan值

import numpy as np
outfile = r'.\iris.data'
# 方法1
iris_data = np.loadtxt(outfile, dtype=object, delimiter=',', skiprows=1)
i, j = iris_data.shape
np.random.seed(20200621)
iris_data[np.random.randint(i, size=20), np.random.randint(j, size=20)] = np.nan
print(iris_data[0:10])
# [['5.1' '3.5' '1.4' '0.2' 'Iris‐setosa']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值