从 Python 中的 .dat-file 读取特定列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29328420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read specific column from .dat-file in Python
提问by Boxiom
I have a results.dat file with some data like this:
我有一个 results.dat 文件,其中包含如下数据:
7522126 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
7825452 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
8073799 0 0 0 0 0 0 -345.551 -140.711 1819.04 -0.0220266 -0.85992 -2.29598
The values are each separated by a tab.
每个值都由制表符分隔。
I want to extract the value in e.g the 8th column for every single line, and save it to an array. So the output should be this:
我想为每一行提取例如第 8 列中的值,并将其保存到一个数组中。所以输出应该是这样的:
-419.795
-419.795
-345.551
What's the easiest way to accomplish this?
实现这一目标的最简单方法是什么?
采纳答案by Nizam Mohamed
with open('results.dat') as f:
[line.split()[7] for line in f]
or define a function,
或定义一个函数,
get_col = lambda col: (line.split('\t')[col-1] for line in open('results.dat'))
Now call the function with desired column number. get_col(8)
gives 8th column data. To store it in array,
现在调用具有所需列号的函数。get_col(8)
给出第 8 列数据。要将其存储在数组中,
array.array('d',map(float,get_col(8)))
回答by Avinash Raj
You could use csv module.
您可以使用csv 模块。
import csv
with open('file') as f:
reader = csv.reader(f, delimiter="\t")
for line in reader:
print(line[7])
回答by lazarus
first of all read the file (result.dat) file in a file object
首先读取文件对象中的文件(result.dat)文件
file = open('result.dat')
now create an empty list
现在创建一个空列表
lst = []
loop through each line of the file
遍历文件的每一行
for line in file:
lst += [line.split()]
now lst is a list of list , where each inner list is a instance (row ) of the result.dat
现在 lst 是一个 list 列表,其中每个内部列表都是 result.dat 的一个实例(行)
now you can extract any column (in your case it is 8th) apply list comprehension for this
现在您可以提取任何列(在您的情况下是第 8 列)为此应用列表理解
column8 = [x[7] for x in lst]
hope this helps,
希望这可以帮助,
回答by Matthew
What's the easiest way to accomplish this?
实现这一目标的最简单方法是什么?
Would recommend numpy.genfromtxt
if the other answers don't suit your needs.
numpy.genfromtxt
如果其他答案不适合您的需求,会推荐。
import numpy
data = numpy.genfromtxt('result.dat', delimiter='\t')
print data[:,7]