<p>我不熟悉从LTspice导出的打印数据,所以我假设您提供的示例行的格式在任何时候都是有效的。在</p>
<p>查看pandas-0.18文档(<a href="http://pandas.pydata.org/pandas-docs/stable/io.html" rel="nofollow">here</a>)的IO工具部分,我没有看到任何现成的解析器实用程序可用于您的数据格式。首先想到的是在填充pandas数据帧之前自己进行解析和准备。在</p>
<p>我假设你的问题的关键部分是解析数据文件,我已经有一段时间没有玩pandas和matplotlib了,所以应该会出现与这些相关的错误。在</p>
<h2>示例</h2>
<p>下面是一个快速的&dirty<em>python3</em>脚本,用于将数据解析到字典列表中,用它构建pandas数据帧,并使用dataframe的<code>plot</code>方法绘制它。我试图解释评论中的步骤:</p>
<pre><code># ltspice.py
""" Use it as:
> python3 ltspice.py /path/to/datafile """
import pandas
import sys
data_header = "Time Gain Degree".split()
# Valid line example:
# 5.00000000000000e+006\t(2.84545891331278e+001dB,8.85405282381414e+001°)
def parse_line(linestr):
# ValueError and IndexError exceptions are used to mark the failure of
# the parse.
try:
# First we split at the '\t' character. This will raise ValueError if
# there is no \t character or there is more than 1 \t
timestr, rest = linestr.split('\t')
# Then we find the indexes of the '(' and ')' in the rest string.
parenst, parenend = (rest.find('(')+1, rest.find(')'))
if (parenst == -1) or (parenend == -1):
# find() method returns -1 if nothing is found, I raise ValueError
# to mark it as a parsing failure
raise ValueError
# rest[parenst:parenend] returns the string inside parens. split method
# splits the string into words separated by the given character (i.e.
# ',')
powstr, degstr = rest[parenst:parenend].split(',')
# converting strings into floats. Replacing units as necessary.
time = float(timestr)
power = float(powstr.replace('dB', ''))
# this will fail with python 2.x
deg = float(degstr.replace('°', ''))
# You can use dict() instead of tuple()
return tuple(zip(data_header, (time, power, deg)))
except (ValueError,IndexError) as e:
return None
def fileparser(fname):
""" A generator function to return a parsed line on each iteration """
with open(fname, mode='r') as fin:
for line in fin:
res = parse_line(line)
if res is not None:
yield res
def create_dataframe(fname):
p = fileparser(fname)
# rec is a tuple of 2-tuples that can be used to directly build a python
# dictionary
recs = [dict(rec) for rec in p]
return pandas.DataFrame.from_records(recs)
if __name__ == '__main__':
data_fname = sys.argv[1]
df = create_dataframe(data_fname)
ax = df.plot(x='Time', y='Gain')
fig = ax.get_figure()
fig.savefig('df.png')
</code></pre>
<p>您可以将此代码复制到文本编辑器,并将其另存为<code>ltspice.py</code>,然后从终端使用<code>python3 ltspice.py yourdata.dat</code>运行它。在</p>
<p>注意,<code>parse_line</code>函数实际上以('key',value)的形式返回一个由2个元组组成的元组,其中'key'代表列名。然后使用这个值在<code>create_dataframe</code>函数中构建字典列表。在</p>
<h2>额外的</h2>
<p>我写了另一个脚本来测试这种行为:</p>
^{pr2}$