时间:2021-07-01 10:21:17 帮助过:4人阅读
在数据分析中经常需要从csv格式的文件中存取数据以及将数据写书到csv文件中。将csv文件中的数据直接读取为dict类型和DataFrame是非常方便也很省事的一种做法,以下代码以鸢尾花数据为例。
代码
- # -*- coding: utf-8 -*-
- import csv
- with open('E:/iris.csv') as csvfile:
- reader = csv.DictReader(csvfile, fieldnames=None) # fieldnames默认为None,如果所读csv文件没有表头,则需要指定
- list_1 = [e for e in reader] # 每行数据作为一个dict存入链表中
- csvfile.close()
- print list_1[0]
输出
- {'Petal.Length': '1.4', 'Sepal.Length': '5.1', 'Petal.Width': '0.2', 'Sepal.Width': '3.5', 'Species': 'setosa'}
如果读入的每条数据需要单独处理且数据量较大,推荐逐条处理然后再放入。
- list_1 = list()
- for e in reader:
- list_1.append(your_func(e)) # your_func为每条数据的处理函数
代码
- # 数据
- data = [
- {'Petal.Length': '1.4', 'Sepal.Length': '5.1', 'Petal.Width': '0.2', 'Sepal.Width': '3.5', 'Species': 'setosa'},
- {'Petal.Length': '1.4', 'Sepal.Length': '4.9', 'Petal.Width': '0.2', 'Sepal.Width': '3', 'Species': 'setosa'},
- {'Petal.Length': '1.3', 'Sepal.Length': '4.7', 'Petal.Width': '0.2', 'Sepal.Width': '3.2', 'Species': 'setosa'},
- {'Petal.Length': '1.5', 'Sepal.Length': '4.6', 'Petal.Width': '0.2', 'Sepal.Width': '3.1', 'Species': 'setosa'}
- ]
- # 表头
- header = ['Petal.Length', 'Sepal.Length', 'Petal.Width', 'Sepal.Width', 'Species']
- print len(data)
- with open('E:/dst.csv', 'wb') as dstfile: #写入方式选择wb,否则有空行
- writer = csv.DictWriter(dstfile, fieldnames=header)
- writer.writeheader() # 写入表头
- writer.writerows(data) # 批量写入
- dstfile.close()
上述代码将数据整体写入csv文件,如果数据量较多且想实时查看写入了多少数据可以使用writerows函数。
代码
- # 读取csv文件为DataFrame
- import pandas as pd
- dframe = pd.DataFrame.from_csv('E:/iris.csv')
也可以稍微曲折点:
- import csv
- import pandas as pd
- with open('E:/iris.csv') as csvfile:
- reader = csv.DictReader(csvfile, fieldnames=None) # fieldnames默认为None,如果所读csv文件没有表头,则需要指定
- list_1 = [e for e in reader] # 每行数据作为一个dict存入链表中
- csvfile.close()
- dfrme = pd.DataFrame.from_records(list_1)
- dfrme.to_csv('E:/dst.csv', index=False) # 不要每行的编号
以上就是详解python读取与写入csv格式文件方法的详细内容,更多请关注Gxl网其它相关文章!