首页 > 解决方案 > 将 txt 文件转换为 numpy 数组

问题描述

我有一个大的 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

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

标签: arraysnumpytext

解决方案


您可以使用numpy.loadtxt

import numpy as np

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

推荐阅读