黑松山资源网 Design By www.paidiu.com
用了两种方式解决该问题,都是网上现有的解决方案。
场景说明:
有一个数据文件,以文本方式保存,现在有三列user_id,plan_id,mobile_id。目标是得到新文件只有mobile_id,plan_id。
解决方案
方案一:用python的打开文件写文件的方式直接撸一遍数据,for循环内处理数据并写入到新文件。
代码如下:
def readwrite1( input_file,output_file): f = open(input_file, 'r') out = open(output_file,'w') print (f) for line in f.readlines(): a = line.split(",") x=a[0] + "," + a[1]+"\n" out.writelines(x) f.close() out.close()
方案二:用 pandas 读数据到 DataFrame 再做数据分割,直接用 DataFrame 的写入功能写到新文件
代码如下:
def readwrite2(input_file,output_file): date_1=pd.read_csv(input_file,header=0,sep=',') date_1[['mobile', 'plan_id']].to_csv(output_file, sep=',', header=True,index=False)
从代码上看,pandas逻辑更清晰。
下面看下执行的效率吧!
def getRunTimes( fun ,input_file,output_file): begin_time=int(round(time.time() * 1000)) fun(input_file,output_file) end_time=int(round(time.time() * 1000)) print("读写运行时间:",(end_time-begin_time),"ms") getRunTimes(readwrite1,input_file,output_file) #直接撸数据 getRunTimes(readwrite2,input_file,output_file1) #使用dataframe读写数据
读写运行时间: 976 ms
读写运行时间: 777 ms
input_file 大概有27万的数据,dataframe的效率比for循环效率还是要快一点的,如果数据量更大些,效果是否更明显呢?
下面试下增加input_file记录的数量试试,有如下结果
input_file readwrite1 readwrite2 27W 976 777 55W 1989 1509 110W 4312 3158
从上面测试结果来看,dataframe的效率提高大约30%左右。
以上这篇Python读csv文件去掉一列后再写入新的文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 林尼攻略一图流
- 李翊君.1993-相思的烈酒【上华】【WAV+CUE】
- 古巨基.1998-LEO.KU(国)【千禧年代】【WAV+CUE】
- 郭子.2001-原来你什么都不想要创作集丫滚石】【WAV+CUE】
- 《使命召唤:黑色行动6》新预告公布!10月25日发售
- Atlus《暗喻幻想》媒体评分汇总:高分好评如潮!
- 2024金摇杆奖提名揭晓 《黑神话》角逐最佳视觉设计!
- 群星《新说唱2024 第3期 (上)》[320K/MP3][32.76MB]
- 群星《新说唱2024 第3期 (上)》[FLAC/分轨][95.38MB]
- 群星《新说唱2024 第3期 (下)》[320K/MP3][31.36MB]
- 幻兽帕鲁手游什么时候正式上线 最新消息一览
- 西普大陆BOSS位置盘点 解锁天启纪元玩法
- 西普大陆精灵进阶培养攻略 精灵养成指南
- dnf手游法控法系职业哪个强 dnf手游法控法系职业强度排行
- 魔兽世界血藤护目镜图纸在哪买 wlk血藤护目镜图纸购买位置介绍