从包含复数的.txt文件中读取列数据的最佳方法是什么?

2024-04-26 05:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,格式如附件所示。5-column data. Colum 0,1: Position coord x,y. Column 3,4,5: Complex fields

几乎有200个数据点。你知道吗

如何以数组的形式高效地读取它们,使a=数组([2,3,…]);d=数组([4+5j,3+1j,…])?你知道吗


Tags: 数据附件格式数组形式文本文件
2条回答

使用熊猫。你知道吗

如果列之间的空格是制表符,那么sep='\t',否则使用Can pandas handle variable-length whitespace as column delimiters中的解决方案

假设它是一个制表符,提取复数第三列的代码类似于

import pandas as pd

df = pd.read_csv('test.txt',sep='\t',skiprows=3)
df.columns = [f'col_{i}' for i in range(len(df.columns))]

column_2_complex_values = df.col_2.map(complex).values # this is a numpy array

看起来您的文本的格式是genfromtxt可以毫无问题地处理的。你知道吗

暂时忽略列名等,示例行将是:

In [235]: txt = """-1.99 -1.99 1.07+0.165j"""

为相应的列指定dtype为float和complex:

In [240]: data = np.genfromtxt([txt,txt],dtype=(float,float,complex))
In [241]: data
Out[241]: 
array([(-1.99, -1.99, 1.07+0.165j), (-1.99, -1.99, 1.07+0.165j)],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<c16')])

结果是一个结构化数组(1d)。按名称访问字段:

In [242]: data['f0']
Out[242]: array([-1.99, -1.99])
In [243]: data['f2']
Out[243]: array([1.07+0.165j, 1.07+0.165j])

熊猫csv阅读器速度更快,但只有200个数据点,我不认为速度会有多大问题。你知道吗

相关问题 更多 >