使用 pandas 从 csv 文件读取全局参数

问题描述 投票:0回答:1

我经常使用 python pandas 来分析实验室的测量数据。例如,如果我有一些“全局”参数“a = 5.2e-3”和“b = 3.21e-5”,它们对于一系列测量有效,其中值 y 是根据 x 进行测量的,但可能是x 和 y 的另一系列测量值有所不同。问题是我必须在 python 文件中定义

a
b
,如下所示:

import pandas as pd

a = 5.2e-3
b = 3.21e-5
d = pd.read_csv('mydata.dat')

def func(a,d):
  ##... calculates something from a and d

其中

mydata.dat
包含

x,y
1,2
3,4
5,6

但是我想在我的数据文件中定义它

mydata.dat
,如下所示:

## Global parameters
a = 5.2e-3
b = 3.21e-5

## Measurement data
x,y
1,2
3,4
5,6

我当然可以编写一个自定义解析器,但我正在寻找一个开箱即用的解决方案。也许语法可能有点不同,但简短而优雅。人们甚至可能会想到另一个类似于 pandas 的库。

那么我该怎么做呢?

python pandas data-analysis scientific-computing
1个回答
0
投票

“..也许语法可能有点不同,但简短而优雅。”

IIUC,您可以尝试使用 builtin 模块

configparser
:

from configparser import ConfigParser

cfg = ConfigParser(allow_no_value=True, default_section=None)
cfg.optionxform = str # case-sensitive keys
cfg.read("mydata.dat")

from io import StringIO
d = pd.read_csv(StringIO("\n".join(cfg["MEASUREMENTS"])))

def fn(d, a):
    return d.mul(float(a))

out = fn(d, cfg["GLOBALS"]["a"]) # or **cfg["GLOBALS"] if `fn` asks for a&b

输出:

print(out)

        x       y
0  0.0052  0.0104
1  0.0156  0.0208
2  0.0260  0.0312

使用的输入(mydata.dat):

[GLOBALS]
a = 5.2e-3
b = 3.21e-5

[MEASUREMENTS]
x,y
1,2
3,4
5,6
© www.soinside.com 2019 - 2024. All rights reserved.