将txt文件转换为numpy数组

时间:2019-05-13 17:04:49

标签: arrays numpy text

我有一个大的txt文件,并通过以下代码提取了其中的一部分: 我提取的数据具有以下结构,我想将包含数字的每一列存储为单独的向量,以进行一些修改。如果有人能告诉我该怎么做,我将非常感激。

code:

coordinate=[]
with open('logfile.txt','r') as file:
    for line in file.readlines():
        if line[0:2]=="Pt":
            coordinate.append(line)
coordinate = [x.strip() for x in coordinate]
coordinate_new=np.array(coordinate)
`````````````````````````````````````````````````````````````````
extracted data:

Pt      13.85929291      -8.31557575     -13.72000000
Pt      13.85929291      -5.54371716     -13.72000000
Pt      13.85929291      -2.77185858     -13.72000000
Pt      13.85929291      -0.00000000     -13.72000000
Pt      13.85929291       2.77185858     -13.72000000
Pt      13.85929291       5.54371716     -13.72000000
Pt      13.85929291       8.31557575     -13.72000000
Pt      13.85929291      11.08743433     -13.72000000
Pt     -12.47336362     -12.47336362       0.00000000
Pt     -12.47336362      -9.70150504       0.00000000
Pt     -12.47336362      -6.92964646       0.00000000
Pt     -12.47336362      -4.15778787       0.00000000
Pt     -12.47336362      -1.38592929       0.00000000
Pt     -12.47336362       1.38592929       0.00000000
Pt     -12.47336362       4.15778787       0.00000000
Pt     -12.47336362       6.92964646       0.00000000
Pt     -12.47336362       9.70150504       0.00000000
Pt     -12.47336362      12.47336362       0.00000000
Pt      -9.70150504     -12.47336362       0.00000000
Pt      -9.70150504      -9.70150504       0.00000000
Pt      -9.70150504      -6.92964646       0.00000000

```````````````````````````````

2 个答案:

答案 0 :(得分:0)

这可能是解决您问题的一种方法,

lists = []
lst_not_append = True

with open('logfile.txt','r') as file:
    lines = file.readlines()
    no = len(lines[0].split())
    if lst_not_append:
        for i in range(no):
            lists.append([])

    for line in lines:
        for i, l in enumerate(line.split()):
            lists[i].append(l)

    arrs = np.array(lists)

注意:arrs2d数组,其每个元素将代表text file的一列。在这里,arrs[0]代表文本文件的first columnarrs[1]代表文本文件的second column,依此类推。该解决方案是通用的,并且可以解决每个文本文件的问题。拥有的列数。

答案 1 :(得分:0)

您可以使用numpy.loadtxt

import numpy as np

c1,c2,c3 = np.loadtxt('logfile.txt', usecols=(1, 2, 3), unpack=True)