arrays - 将 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
```````````````````````````````
解决方案
您可以使用numpy.loadtxt
:
import numpy as np
c1,c2,c3 = np.loadtxt('logfile.txt', usecols=(1, 2, 3), unpack=True)
推荐阅读
- asp.net-core - ASP.NET Core 自定义验证错误消息未本地化
- c++ - kill syscommand 在 Catch2 测试用例中产生失败
- c++ - 数组升序排序嵌套循环问题
- apache-camel - 在 Apache Camel 2.21.5 Olingo4 组件中使用 httpclientBuilder
- angular - Angular 中使用的语法是什么,例如:@NgModule 和 @Component 以及 @Injectable?(使用@符号声明)
- google-apps-script - sheet.isRowHiddenByFilter(n) 不能与切片器一起使用吗?
- php - 是否有任何解决方案可以使用 PHP 在 foreach 中使用不同的变量运行相同的查询?
- python - 如果端口更改,容器化烧瓶应用程序不会加载
- c# - c# GetDirectories 返回意外目录(给出具体示例)
- javascript - 如何查询自定义 HTML 元素?