Python读csv文件去掉一列后再写入新的文件实例
作者:卡路西法 时间:2022-05-13 14:04:12
用了两种方式解决该问题,都是网上现有的解决方案。
场景说明:
有一个数据文件,以文本方式保存,现在有三列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%左右。
来源:https://www.cnblogs.com/kaluxifa/archive/2017/12/28/8134960.html
标签:Python,csv,写入,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现Dijkstra算法的最短路径问题
2023-05-18 23:22:15
![](https://img.aspxhome.com/file/2023/4/95784_0s.png)
使用Selenium破解新浪微博的四宫格验证码
2021-06-16 11:22:28
![](https://img.aspxhome.com/file/2023/9/76869_0s.png)
利用Python实现学生信息管理系统的完整实例
2022-03-12 10:35:03
![](https://img.aspxhome.com/file/2023/9/79619_0s.png)
asp禁止站外盗链、判断星期几方法
2007-10-02 12:58:00
python实现图像拼接
2023-07-26 15:38:27
![](https://img.aspxhome.com/file/2023/9/60969_0s.jpg)
如何检测用户第一次访问我的网站并显示友好信息?
2009-11-25 20:33:00
Go语言HTTPServer开发的六种方式小结
2023-06-22 21:48:21
Zabbix实现微信报警功能
2021-10-17 04:40:05
![](https://img.aspxhome.com/file/2023/7/115227_0s.png)
Python3实现带附件的定时发送邮件功能
2023-07-08 23:33:57
Python Socket传输文件示例
2023-10-18 17:19:00
分享216色网页拾色器(调色板)
2007-09-27 12:33:00
![](https://img.aspxhome.com/file/UploadPic/20079/27/2007927124954557s.jpg)
PHP基础用法讲解及phpinfo();演示
2023-05-29 08:34:29
![](https://img.aspxhome.com/file/2023/3/55373_0s.jpg)
python 实现提取PPT中所有的文字
2023-05-01 04:21:35
![](https://img.aspxhome.com/file/2023/7/81637_0s.gif)
Python排序搜索基本算法之归并排序实例分析
2023-10-19 04:15:11
![](https://img.aspxhome.com/file/2023/7/98897_0s.jpg)
Python制作数据导入导出工具
2023-07-25 06:59:59
Python 获取当前所在目录的方法详解
2021-07-19 09:41:14
OpenCV 图像梯度的实现方法
2023-07-14 08:25:43
![](https://img.aspxhome.com/file/2023/6/64296_0s.png)
pycharm 配置svn的图文教程(手把手教你)
2022-10-21 18:47:47
![](https://img.aspxhome.com/file/2023/7/83697_0s.jpg)
python openpyxl使用方法详解
2021-12-23 14:49:18
python数据操作之lambda表达式详情
2022-08-19 21:21:32