Python 实训 1 计算 iris 数据值的均值
作者:互联网
又得到徒弟的求救,让我帮他做作业,现在的大学生到底是怎么了???
Python这门课,学起来挺有意思的,自己咋不学着敲代码呢?老是来让我帮
你写,那就再写一次吧,帮你写个作业没问题,看完答案给个赞啊要记得!
答案源码:
复制拿走,
留下你的赞 !!!
谢谢。。。
注:在此提醒各大学生,复制拿走之后修改一下里面的变量什么的,至少把一些名字改了吧,要不然你们班太多学生拿了这答案怕你们老师发现雷同就不好了呢~
其实是收到粉丝的求助,要我写这题的答案,我就找我徒弟要了题目。来帮你们完成。
补充:在使用下方代码时,需要安装numpy库,要不然,无法运行成功。
安装方法:
打开pycharm,下方有个终端窗口
在此运行:
python -m pip install numpy
输入命令,回车等待下载安装即可。
如果上诉命令执行不了,那么你需要更新一下你的pip:
python -m pip install --upgrade pip
升级一下pip版本即可。
然后就是代码里的文件路径,复制拿走之后,写你们自己文件存放的路径,大学生啊大学生,答应我,动一动脑子好吗?
好了,上诉步骤做了之后,你就可以拿着代码运行交作业啦
import csv
import numpy as np
fileN = 'C:\\Users\\HP\\Desktop\\iris.csv'
with open(fileN,'r') as FileN:
reader = csv.DictReader(FileN)
Sepal1 = [row['Sepal.Length'] for row in reader]
Sepal_1 = []
for col1 in Sepal1:
Sepal_1.append(float(col1))
FileN.close()
print(np.mean(Sepal_1))
with open(fileN, 'r') as FileN:
reader = csv.DictReader(FileN)
Sepal2 = [row['Sepal.Width'] for row in reader]
Sepal_2 = []
for col2 in Sepal2:
Sepal_2.append(float(col2))
FileN.close()
print(np.mean(Sepal_2))
with open(fileN, 'r') as FileN:
reader = csv.DictReader(FileN)
Petal1 = [row['Petal.Length'] for row in reader]
Petal_1 = []
for col3 in Petal1:
Petal_1.append(float(col3))
FileN.close()
print(np.mean(Petal_1))
with open(fileN, 'r') as FileN:
reader = csv.DictReader(FileN)
Petal2 = [row['Petal.Width'] for row in reader]
Petal_2 = []
for col4 in Petal2:
Petal_2.append(float(col4))
FileN.close()
print(np.mean(Petal_2))
with open(fileN, 'r') as FileN:
reader = csv.DictReader(FileN)
iris1 = [iris_item for iris_item in reader]
file_name = 'C:\\Users\\HP\\Desktop\\my_iris.csv'
my_key = []
for i in iris1[0].keys():
my_key.append(i)
with open(file_name, 'w', newline = '') as f:
write_csv = csv.DictWriter(f, my_key)
write_csv.writeheader()
write_csv.writerows(iris1)
csvFile = open("C:\\Users\\HP\\Desktop\\my_iris.csv", "a")
fileheader = ["Sepal.Length平均值"]
dict_writer = csv.DictWriter(csvFile, fileheader)
dict_writer.writerow(dict(zip(fileheader, fileheader)))
dict_writer.writerow({"Sepal.Length平均值": np.mean(Sepal_1)})
fileheader = ["Sepal.Width平均值"]
dict_writer = csv.DictWriter(csvFile, fileheader)
dict_writer.writerow(dict(zip(fileheader, fileheader)))
dict_writer.writerow({"Sepal.Width平均值": np.mean(Sepal_2)})
fileheader = ["Petal.Length平均值"]
dict_writer = csv.DictWriter(csvFile, fileheader)
dict_writer.writerow(dict(zip(fileheader, fileheader)))
dict_writer.writerow({"Petal.Length平均值": np.mean(Petal_1)})
fileheader = ["Petal.Width平均值"]
dict_writer = csv.DictWriter(csvFile, fileheader)
dict_writer.writerow(dict(zip(fileheader, fileheader)))
dict_writer.writerow({"Petal.Width平均值": np.mean(Petal_2)})
csvFile.close()
欢迎关注公众号【夜来疏影】
标签:iris,fileheader,Python,Petal,Sepal,dict,实训,csv,FileN 来源: https://blog.csdn.net/weixin_43729943/article/details/105652001