【问题标题】:Extract multiple arrays from .DAT file with undefined size从 .DAT 文件中提取多个未定义大小的数组
【发布时间】:2016-03-11 08:37:26
【问题描述】:

我有一个在 .DAT 文件中存储三个数据集的设备,它们始终具有相同的标题和列数,但行数不同。 它们是 (n x 4)、(m x 4)、(L x 3)。 我需要将三个数据集提取到单独的数组中进行绘图。 我一直在尝试使用 numpy.genfromtxt 和 numpy.loadtxt,但让它们适用于这种格式的唯一方法是手动定义每个数据集开始的行。 因为我经常需要处理这种格式,所以我一直在尝试自动化它。 如果有人可以建议一种可能有效的方法,我将不胜感激。我附上了一个示例文件。

example file

【问题讨论】:

    标签: python arrays numpy matplotlib


    【解决方案1】:

    只是一个快速而肮脏的解决方案。以您的文件大小,您可能会遇到性能问题。如果你知道mnL,用各自的长度初始化输出向量。

    这里是策略:将整个文件加载到一个变量中。逐行读取变量。一旦你发现一个关键词,就举起一个标志,表明你在特定的区块中。在下一行中,读出该行到正确的变量。

    isblock1 = isblock2 = isblock3 = False
    fout = [] # construct also all the other variables that you want to collect.
    with open(file, 'r') as file:
        lines = file.readlines() #read all the lines
    for line in lines:
        if isblock1:
            (f, psd, ipj, itj) = line.split()
            fout.append(f) #do this also with the other variables
        if isblock2:
            (t1, p1, p2, p12) = line.split()
        if isblock3:
            (t2, v1, v2) = line.split()
        if 'Frequency' is in line:
            isblock1 = True
            isblock2 = isblock3 = False
        if 'Phasor' is in line:
            isblock2 = True
            isblock1 = isblock3 = False
        if 'Voltage' is in line:
            isblock3 = True
            isblock1 = isblock2 = False
    

    希望对您有所帮助。

    【讨论】:

    • 是的,这正是我所需要的,性能不是问题,我不介意多等几秒钟,这比手动输入数组大小要快谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多