尝试用python解析文本文件进行数据分析

2023-12-11

我在 Perl 中做了很多数据分析,并尝试使用 pandas、numpy、matplotlib 等在 python 中复制这项工作。

一般工作流程如下:

1)glob目录中的所有文件

2)解析文件,因为它们有元数据

3)使用正则表达式来隔离给定文件中的相关行(它们通常以“LOOPS”等标签开头)

4)分割与标签匹配的行并将数据加载到哈希中

5)做一些数据分析

6)绘制一些图

以下是我通常在 Perl 中执行的示例:

print"Reading File:\n";                              # gets data
foreach my $vol ($SmallV, $LargeV) {
  my $base_name = "${NF}flav_${vol}/BlockedWflow_low_${vol}_[0-9].[0-9]_-0.25_$Mass{$vol}.";
  my @files = <$base_name*>;                         # globs for file names
  foreach my $f (@files) {                           # loops through matching files
    print"... $f\n";
    my @split = split(/_/, $f);
    my $beta = $split[4];
    if (!grep{$_ eq $beta} @{$Beta{$vol}}) {         # constructs Beta hash
      push(@{$Beta{$vol}}, $split[4]);
    }
    open(IN, "<", "$f") or die "cannot open < $f: $!"; # reads in the file
    chomp(my @in = <IN>);
    close IN;
    my @lines = grep{$_=~/^LOOPS/} @in;       # greps for lines with the header LOOPS
    foreach my $l (@lines) {                  # loops through matched lines
      my @split = split(/\s+/, $l);           # splits matched lines
      push(@{$val{$vol}{$beta}{$split[1]}{$split[2]}{$split[4]}}, $split[6]);# reads data into hash
      if (!grep{$_ eq $split[1]} @smearingt) {# fills the smearing time array
        push(@smearingt, $split[1]);
      }
      if (!grep{$_ eq $split[4]} @{$block{$vol}}) {# fills the number of blockings
        push(@{$block{$vol}}, $split[4]);
      }
    }
  }
  foreach my $beta (@{$Beta{$vol}}) {
    foreach my $loop (0,1,2,3,4) {         # loops over observables
      foreach my $b (@{$block{$vol}}) {    # beta values
        foreach my $t (@smearingt) {       # and smearing times
          $avg{$vol}{$beta}{$t}{$loop}{$b} = stat_mod::avg(@{$val{$vol}{$beta}{$t}{$loop}{$b}});     # to find statistics
          $err{$vol}{$beta}{$t}{$loop}{$b} = stat_mod::stdev(@{$val{$vol}{$beta}{$t}{$loop}{$b}});
        }
      }
    }
  }
}
print"File Read in Complete!\n";

我希望将此数据加载到分层索引数据结构中,其中 perl 哈希的索引成为我的 python 数据结构的索引。到目前为止,我遇到的 pandas 数据结构的每个示例都经过精心设计,其中整个结构(索引和值)都是在一个命令中手动分配的,然后进行操作以演示数据结构的所有功能。不幸的是,我无法一次分配所有数据,因为我不知道要分析的数据中有哪些质量、β、大小等。我这样做的方式不对吗?有谁知道更好的方法吗?数据文件是不可变的,我必须使用我了解如何做的正则表达式来解析它们。我需要帮助是将数据放入适当的数据结构中,以便我可以取平均值、标准差、执行数学运算并绘制数据图。

典型数据的标题行数未知,但我关心的内容如下所示:

Alpha 0.5 0.5 0.4
Alpha 0.5 0.5 0.4
LOOPS 0 0 0 2 0.5 1.7800178
LOOPS 0 1 0 2 0.5 0.84488326
LOOPS 0 2 0 2 0.5 0.98365135  
LOOPS 0 3 0 2 0.5 1.1638834
LOOPS 0 4 0 2 0.5 1.0438407
LOOPS 0 5 0 2 0.5 0.19081102
POLYA NHYP 0 2 0.5 -0.0200002 0.119196 -0.0788721 -0.170488 
BLOCKING COMPLETED
Blocking time 1.474 seconds
WFLOW 0.01 1.57689 2.30146 0.000230146 0.000230146 0.00170773 -0.0336667
WFLOW 0.02 1.66552 2.28275 0.000913101 0.00136591 0.00640552 -0.0271222
WFLOW 0.03 1.75 2.25841 0.00203257 0.00335839 0.0135 -0.0205722
WFLOW 0.04 1.83017 2.22891 0.00356625 0.00613473 0.0224607 -0.0141664
WFLOW 0.05 1.90594 2.19478 0.00548695 0.00960351 0.0328218 -0.00803792
WFLOW 0.06 1.9773 2.15659 0.00776372 0.0136606 0.0441807 -0.00229793
WFLOW 0.07 2.0443 2.1149 0.010363 0.018195 0.0561953 0.00296648

我(认为)我想要的,我用 think 作为序言,因为我是 python 新手,专家可能知道更好的数据结构,是一个分层索引系列,如下所示:

volume   mass   beta   observable   t   value

1224     0.0    5.6    0            0   1.234
                                    1   1.490
                                    2   1.222
                       1            0   1.234
                                    1   1.234
2448     0.0    5.7    0            1   1.234

等等:http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-hierarchical

对于那些不了解 perl 的人:

我需要的主要内容是:

push(@{$val{$vol}{$beta}{$split[1]}{$split[2]}{$split[4]}}, $split[6]);# reads data into hash

我这里有一个名为“val”的哈希值。这是数组的哈希值。我相信用Python语言来说这将是一个列表字典。这里的每件事看起来都是这样的: '{$something}' 是散列 'val' 中的键,我将变量 $split[6] 中存储的值附加到指定散列元素的数组末尾通过所有 5 个键。这是我的数据的根本问题,因为我感兴趣的每个数量都有很多键。

=========

UPDATE

我想出了以下导致此错误的代码:

Traceback (most recent call last):
  File "wflow_2lattice_matching.py", line 39, in <module>
    index = MultiIndex.from_tuples(zipped, names=['volume', 'beta', 'montecarlo_time, smearing_time'])
NameError: name 'MultiIndex' is not defined

Code:

#!/usr/bin/python

from pandas import Series, DataFrame
import pandas as pd
import glob
import re
import numpy

flavor = 4
mass = 0.0

vol = []
b = []
m_t = []
w_t = []
val = []

#tup_vol = (1224, 1632, 2448)
tup_vol = 1224, 1632
for v in tup_vol:
  filelist = glob.glob(str(flavor)+'flav_'+str(v)+'/BlockedWflow_low_'+str(v)+'_*_0.0.*')
  for filename in filelist:
    print 'Reading filename:  '+filename
    f = open(filename, 'r')
    junk, start, vv, beta, junk, mass, mont_t = re.split('_', filename)
    ftext = f.readlines()
    for line in ftext:
      if re.match('^WFLOW.*', line):
        line=line.strip()
        junk, smear_t, junk, junk, wilson_flow, junk, junk, junk = re.split('\s+', line)
        vol.append(v)
        b.append(beta)
        m_t.append(mont_t)
        w_t.append(smear_t)
        val.append(wilson_flow)
zipped = zip(vol, beta, m_t, w_t)
index = MultiIndex.from_tuples(zipped, names=['volume', 'beta', 'montecarlo_time, smearing_time'])
data = Series(val, index=index)

您将得到以下信息:

NameError: name 'MultiIndex' is not defined

因为当您导入Series和DataFrame时,您没有直接导入MultiIndex。

你有 -

from pandas import Series, DataFrame

你需要 -

from pandas import Series, DataFrame, MultiIndex

或者您可以使用 pd.MultiIndex 来引用 MultiIndex,因为您将 pandas 导入为 pd

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试用python解析文本文件进行数据分析 的相关文章

随机推荐