您的位置:首页 > 编程语言 > Python开发

Python学习(十九)——CSV文件读写

2017-12-04 16:15 447 查看
CSV文件读写

写入CSV文件

创建w.csv文件,并将iris数据写入

#!/usr/bin/python
# -*-coding:utf-8-*-
import numpy as np
import csv
from sklearn.datasets import load_iris
iris = load_iris()

writer = csv.writer(file('w.csv', 'wb'))
# 在首行写入对应数据名称
writer.writerow(['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width', 'Target'])
# 写入iris数据
for i in xrange(len(iris.data)):
l = np.hstack((np.array(iris.data[i]), np.array(iris.target[i])))
writer.writerow(l)
print l


输出:

[ 5.1  3.5  1.4  0.2  0. ]
[ 4.9  3.   1.4  0.2  0. ]
[ 4.7  3.2  1.3  0.2  0. ]
[ 4.6  3.1  1.5  0.2  0. ]
.
.
.
[ 5.6  2.7  4.2  1.3  1. ]
[ 5.7  3.   4.2  1.2  1. ]
[ 5.7  2.9  4.2  1.3  1. ]


打开w.csv文件可以看到其中的数据存放形式:



读取CSV文件

读取w.csv数据

由于直接读取CSV文件内的数据时数据是以字符串类型存放在list内返回的,因此要将读取的list内的字符串转化为float数据,然后转换为矩阵,最后将其分离为data和target,以便于后期对其进行处理:

# CSV文件读取
import numpy as np
import csv
l = []
with open('w.csv') as file:
lines = csv.reader(file)
for line in lines:
l.append(line)
# 去除第1行,即写入时添加的'Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width', 'Target'
l.remove(l[0])

iris = []
for i in l:
# 将list内的字符串转化为float数据
iris.append(map(float, i))
# 转换为矩阵
iris = np.mat(np.array(iris))
# 获得数据
data = iris[:,0:-1]
# 获得数据labels
target = iris[:,-1]
print 'data:\n', data
print 'target:\n', target


输出:

data:
[[ 5.1  3.5  1.4  0.2]
[ 4.9  3.   1.4  0.2]
[ 4.7  3.2  1.3  0.2]
.
.
.
[ 6.5  3.   5.2  2. ]
[ 6.2  3.4  5.4  2.3]
[ 5.9  3.   5.1  1.8]]
target:
[[ 0.]
[ 0.]
[ 0.]
.
.
.
[ 2.]
[ 2.]
[ 2.]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: