python/机器学习:读写机器学习中常用的.CSV数据文件t
2015-07-17 21:04
816 查看
最近在kaggle上做题,常用到.CSV数据文件。下面给出读写此类文件的代码:
读文件:
写文件:
加载完了数据,就可以使用scikit-learn介绍的方法处理数据啦。。。
读文件:
global trainIdDict trainIdDict = {} global lineCount lineCount = 0 import csv csvfile = file('train_set.csv', 'rb') reader = csv.reader(csvfile) for line in reader: lineCount += 1 if lineCount==1: #过滤标题行 continue ID = line[0] quantity = int(line[2]) cost = float(line[3]) if trainIdDict.has_key(ID): trainIdDict[ID][0] += quantity trainIdDict[ID][1] += cost*quantity else: trainIdDict[ID] = [quantity, cost*quantity] else: trainQuantityDict[quantity] = [1, cost] #第一个量记录quantity出现了几次 csvfile.close()
写文件:
import csv csvfile = file('train_set_processResult.csv', 'wb') writer = csv.writer(csvfile, dialect='excel') for key in trainIdDict.keys(): aveCost = trainIdDict[key][1] / (trainIdDict[key][0]*1.0) #每一个产品的averageCost writer.writerow([str(key), str(trainIdDict[key][0]), str(trainIdDict[key][1]), str(aveCost)]) csvfile.close()
加载完了数据,就可以使用scikit-learn介绍的方法处理数据啦。。。
相关文章推荐
- python各种类型转换
- 在python中使用liblinear
- python 脚本在cmd下运行
- 【LeetCode】Python requests模拟Leetcode登陆
- Python中的copy()方法为“浅复制”
- python映射关系
- 通过邮件发送running process输出最后N行
- Python之HTML的解析(网页抓取一)
- python-布尔运算
- Python笔记---Ubuntu 下使用 Python
- python内置函数大全
- Spark+Python lab1
- 推荐系统
- Google's Python Class(三)——Python 列表
- Windows下Python添加库(模块)路径
- Python: classmethod类函数 & staticmethod静态函数 区别
- python中的继承
- Python的Django框架中的表单处理示例
- Python中max函数用法实例分析
- python中的input函数和raw_input函数的区别