Python读写csv文件
媒介
逗号分隔值(Co妹妹a-Separated Values,CSV,有时也称为字符分隔值,由于分隔字符也能够没有是逗号),其文件以纯文本方式存储表格数据(数字以及文本)。纯文本象征着该文件是一个字符序列,没有含必需像二进制数字那样被解读的数据。CSV文件由恣意数量的记载组成,记载间以某种换行符分隔;每一笔记录由字段组成,字段间的分隔符是其它字符或字符串,最多见的是逗号或制表符。通常,一切记载都有齐全相反的字段序列.
特性
读掏出的数据普通为字符类型,假如是数字需求工钱转换为数字
以行为单元读取数据
列之间以半角逗号或制表符为分隔,普通为半角逗号
普通为每一行扫尾没有空格,第一行是属性列,数据列之间以距离符为距离无空格,行之间无空行。
行之间无空行非常首要,假如有空行或许数据集中行末有空格,读取数据时普通会犯错,诱发[list index out of range]谬误。PS:曾经被这个谬误坑过不少次!
应用python I/O写入以及读取CSV文件
应用PythonI/O写入csv文件
如下是将"birthweight.dat"低出身体重的dat文件从作者源处下载上去,而且将其解决后保留到csv文件中的代码。
import csv import os import numpy as np import random import requests # name of data file # 数据集称号 birth_weight_file = 'birth_weight.csv' # download data and create data file if file does not exist in current directory # 假如以后文件夹下不birth_weight.csv数据集则下载dat文件并天生csv文件 if not os.path.exists(birth_weight_file): birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat' birth_file = requests.get(birthdata_url) birth_data = birth_file.text.split('\r\n') # split宰割函数,以一行作为宰割函数,windows中换行符号为'\r\n',每一一行前面都有一个'\r\n'符号。 birth_header = birth_data[0].split('\t') # 每一一列的题目,标正在第一行,便是birth_data的第一个数据。并应用制表符作为划分。 birth_data = [[float(x) for x in y.split('\t') if len(x) >= 1] for y in birth_data[1:] if len(y) >= 1] print(np.array(birth_data).shape) # (189, 9) # 此为list数据方式没有是numpy数组不克不及应用np,shape函数,然而咱们能够应用np.array函数将list工具转化为numpy数组后应用shape属性进行查看。 with open(birth_weight_file, "w", newline='') as f: # with open(birth_weight_file, "w") as f: writer = csv.writer(f) writer.writerows([birth_header]) writer.writerows(birth_data) f.close()
常见谬误list index out of range
此中咱们重点需求讲的是 with open(birth_weight_file, "w", newline='') as f: 这个语句。示意写入csv文件,假如没有加之参数 newline='' 示意以空格作为换行符,而是用 with open(birth_weight_file, "w") as f: 语句。则天生的表格中会呈现空行。
不只仅是用python I/O进行csv数据的读写时,行使其他办法读写csv数据,或许从网上下载好csv数据集后都需求查看其每一行后有无空格,或许有无过剩的空行。防止不用要的谬误~影响数据剖析时的判别。
应用PythonI/O读取csv文件
应用python I/O办法进行读取时便是新建一个List 列表而后依照后行后列的程序(相似C言语中的二维数组)将数据存进空的List工具中,假如需求将其转化为numpy 数组也能够应用np.array(List name)进行工具之间的转化。
birth_data = [] with open(birth_weight_file) as csvfile: csv_reader = csv.reader(csvfile) # 应用csv.reader读取csvfile中的文件 birth_header = next(csv_reader) # 读取第一行每一一列的题目 for row in csv_reader: # 将csv 文件中的数据保留到birth_data中 birth_data.append(row) birth_data = [[float(x) for x in row] for row in birth_data] # 将数据从string方式转换为float方式 birth_data = np.array(birth_data) # 将list数组转化成array数组便于查看数据构造 birth_header = np.array(birth_header) print(birth_data.shape) # 行使.shape查看构造。 print(birth_header.shape) # # (189, 9) # (9,)
应用Pandas读取CSV文件
import pandas as pd csv_data = pd.read_csv('birth_weight.csv') # 读取训练数据 print(csv_data.shape) # (189, 9) N = 5 csv_batch_data = csv_data.tail(N) # 取后5条数据 print(csv_batch_data.shape) # (5, 9) train_batch_data = csv_batch_data[list(range(3, 6))] # 取这20条数据的3到5列值(索引从0开端) print(train_batch_data) # RACE SMOKE PTL # 184 0.0 0.0 0.0 # 185 0.0 0.0 1.0 # 186 0.0 1.0 0.0 # 187 0.0 0.0 0.0 # 188 0.0 0.0 1.0
应用Tensorflow读取CSV文件
自己正在平常普通都是应用Tensorflow解决各种数据,以是关于应用Tensorflow读取数据正在此不外多的进行诠释,上面贴上一段代码。
'''应用Tensorflow读取csv数据''' filename = 'birth_weight.csv' file_queue = tf.train.string_input_producer([filename]) # 设置文件名行列步队,这样做可以批量读取文件夹中的文件 reader = tf.TextLineReader(skip_header_lines=1) # 应用tensorflow文本行浏览器,而且设置疏忽第一行 key, value = reader.read(file_queue) defaults = [[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.]] # 设置列属性的数据格局 LOW, AGE, LWT, RACE, SMOKE, PTL, HT, UI, BWT = tf.decode_csv(value, defaults) # 将读取的数据编码为咱们设置的默许格局 vertor_example = tf.stack([AGE, LWT, RACE, SMOKE, PTL, HT, UI]) # 读获得到的两头7列属性为训练特色 vertor_label = tf.stack([BWT]) # 读获得到的BWT值示意训练标签 # 用于给掏出的数据增加上batch_size维度,以批解决的形式读出数据。能够设置批解决数据巨细,能否反复读取数据,容量巨细,行列步队末尾巨细,读取线程等属性。 example_batch, label_batch = tf.train.shuffle_batch([vertor_example, vertor_label], batch_size=10, capacity=100, min_after_dequeue=10) # 初始化Session with tf.Session() as sess: coord = tf.train.Coordinator() # 线程治理器 threads = tf.train.start_queue_runners(coord=coord) print(sess.run(tf.shape(example_batch))) # [10 7] print(sess.run(tf.shape(label_batch))) # [10 1] print(sess.run(example_batch)[3]) # [ 19. 91. 0. 1. 1. 0. 1.] coord.request_stop() coord.join(threads) ''' 关于应用一切Tensorflow的I/O操作来讲开启以及封闭线程治理器都是须要的操作 with tf.Session() as sess: coord = tf.train.Coordinator() # 线程治理器 threads = tf.train.start_queue_runners(coord=coord) # Your code here~ coord.request_stop() coord.join(threads) '''
另有其余应用python读取文件的各类办法,这里引见三种,没有活期进行增补。
以上就是python怎样读取csv文件的具体内容,更多请存眷资源魔其它相干文章!
标签: Python csv python教程 python编程 python使用问题
抱歉,评论功能暂时关闭!