如何使用python从csv文件解析特定的数字数据 [英] How to parse specific numeric data from csv file using python

查看:360
本文介绍了如何使用python从csv文件解析特定的数字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天。


我在cvs文件中有一系列数据如下,


1 ,,,

1,137.1,1198,1.6

2,159,300,0.4

3,176,253,0.3

4,197,231,0.3

5,198,525 ,0.7

6,199,326,0.4

7,215,183,0.2

8,217.1,178,0.2

9,244.2,416,0.5

10,245.1,316,0.4

我想从第二列中提取特定数据,例如217.1和245.1,并将它们连接成一个新文件,如


8,217.1,178,0.2

10,245.1,316,0.4


我用cvs模块读取我的cvs文件但是,我无法按照自己的意愿提取具体数据。有谁可以请帮助我。谢谢。

Good day.

I have series of data in cvs file like below,

1,,,
1,137.1,1198,1.6
2,159,300,0.4
3,176,253,0.3
4,197,231,0.3
5,198,525,0.7
6,199,326,0.4
7,215,183,0.2
8,217.1,178,0.2
9,244.2,416,0.5
10,245.1,316,0.4

I want to extract specific data from second column for example 217.1 and 245.1 and have them concatenated into a new file like,

8,217.1,178,0.2
10,245.1,316,0.4

I use cvs module to read my cvs file, but, I can''t extract specific data as I desire. Could anyone kindly please help me. Thank you.

推荐答案

只需打开cvs文件,打开第二个cvs文件进行编写。


然后循环执行第一个cvs文件(对于fileobject中的行),并检查第二列中的数据是否符合您的条件。如果是,请将该行写入第二个cvs文件。


就个人而言,如果你的数据真的像你建议的那样简单,我就不会打扰cvs文件了,只需使用内置的open,read,write和close命令。应该只是少数几行。如果你正在努力,请回复你所尝试的内容,我会写出一个代码示例。我现在急着走,我很害怕。
Just open the cvs file, and open a second cvs file to write.

Then loop through the first cvs file, (for line in fileobject), and check whether the data in the second column matches your criteria. If it does, write the line to the second cvs file.

Personally, if your data is really as simple as you suggest, I wouldn''t bother with the cvs file, and just use the built in open, read, write and close commands. Should only be a handful of lines. If you''re struggling, post back with what you''ve tried, and I''ll write out an example of the code. I''m rushing now, though, I''m afraid.


+1打开它作为普通文件并在逗号上拆分。此外,在执行任何其他操作之前,请检查每个拆分记录的长度。你不应该依赖它们不是文件中任何空的或格式错误的记录。
+1 on opening it as a normal file and splitting on the comma. Also, check the length of each split record before doing anything else. You should not rely on their not being any empty or malformed records in the file.


@Glenton


亲爱的Glenton,


实际上我正在处理我的csv文件中的10K行数据。我会试试你的建议。谢谢你的回复。
@Glenton
Dear Glenton,

Actually I''m dealing with 10K rows of data in my csv file. I will try your suggestion. Thanks for prompt replied.


这篇关于如何使用python从csv文件解析特定的数字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆