python - 只读取包含大量列的大型文本数据文件的最后一列

标签 python

我是 Python 的新手。 我正在编写一个用于数据分析的 jupyter notebook,它应该可以处理已经提供的数据文件。 这些数据文件 (.txt) 每个都包含一个大的 float 表,带有分隔符“”。它们很丑陋,因为它们的行数相对较少(~2k)而列数很多(~100k)。 “单文件”详分割析工作正常(我有足够的 RAM 将这些文件之一完全加载到内存中,例如通过 np.loadtxt(),并对其进行处理);但我随后想尝试进行多文件交叉分析,其中我只对每个文件的最后一列感兴趣。我找不到一种快速/高效/好的方法来做到这一点。

我能做的是一次一个地 np.loadtxt() 这些文件,然后每次复制结果数组的最后一列并删除其余的;并重复。这是痛苦的缓慢,但它的工作。我想知道我是否可以做得更好!

我也试过这个,灵感来 self 在网上搜索的东西:

data=[]
for i in range(N_istar):
    for j in range(N_col_pos):
        with open(filename(i,j), 'r') as f:
            lastcol=[]
            line=f.readline()
            while line:
                sp=line.split()
                lastcol.append(sp[-1])
            data.append(lastcol)

但这要么永远持续下去,要么花费大量时间。

有什么建议吗?

最佳答案

您可以使用 pandas read_csv(usecols=)。您必须知道列的索引或名称。代码简洁明了,请参见下面的示例。

如果您不知道最后一列的索引,您可以读取第一行并计算分隔符的数量。

示例

测试.csv

a  b   c    d
0  1   2    3
2  4   6    8

python 代码

import pandas as pd

seperator = r"\s*"  # default this will be ",". Using a regex does make it slower.

# column names
pd.read_csv('test.csv', sep=seperator, usecols=['d'])

# column index
pd.read_csv('test.csv', sep=seperator, header=None, usecols=[3])

# Unknown number of columns
with open('test.csv') as current_file:
    last_column_index = len(current_file.readline().split())
pd.read_csv('test.csv', sep=seperator, header=None, usecols=[last_column_index])

关于python - 只读取包含大量列的大型文本数据文件的最后一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57569314/

相关文章:

python - Apache Spark : Error while starting PySpark

python - 为什么管道被用作 GridsearchCV 的一部分,而不是相反?

python - 导入错误 : cannot import name 'binary_type'

python - 无法在 Kivy 中设置布局大小

python - 从pytables中的多个表中选择数据

python - OSx 更新后如何修复损坏的 python 2.7.11

python - 从数据框列表中访问元素的名称

python - 如何统计列表中重复项的出现次数和次数?

python - 将字节数组写入文件?

python - 索引数据框