python3 - 从文本文件格式导入数据框 head1=value|head2=value

python3 - import dataframe from textfile format head1=value|head2=value

我查看了 pandas 文档,有几个选项可以将数据导入 pandas 数据框。在导入文本文件时,常见的方法似乎是导入 csv 文件。

我想使用的数据是格式如下的日志文件:

timestamp=2018-09-08T11:11:58.362028|head1=value|head2=value|head3=value
timestamp=2018-09-08T11:15:25.860244|head1=value|head2=value|head3=value

我只需要将这些元素中的一些导入到数据时间范围内,比如时间戳、head1 和 head3。

在 csv 符号中,数据框如下所示:

timestamp;head1;head3
logfile row1 - value of timestamp; value of head1; value of head3
logfile row2 - value of timestamp; value of head1; value of head3
logfile row3 - value of timestamp; value of head1; value of head3

我可以使用这些数据编写一个 csv 文件,然后将其导入。但是是否有 pandas 函数或直接方法将这些数据导入 pandas 数据框?

提前感谢您的帮助!

你可以这样做:

 columns = ['timestamp','head1','head2','head3']
 pd.read_csv(your_file.csv,sep='|',names = columns).drop('head2',1).replace('.*=','',regex=True)

我会像这样解析和处理文件:

with open('file.csv', 'r') as fh:
  df = pd.DataFrame([dict(x.split('=') for x in l.strip().split('|')) for l in fh])
  df = df[['timestamp', 'head1', 'head3']]

df

                    timestamp  head1  head3
0  2018-09-08T11:11:58.362028  value  value
1  2018-09-08T11:15:25.860244  value  value

感谢您提供出色的解决方案!我使用了提供的解决方案,但在导入期间已经过滤了所需的行,因此日志文件中的其他不同结构化元素不会打扰:

import pandas as pd
with open('logfile.txt', 'r') as fh:
  df = pd.DataFrame([dict(x.split('=') for x in l.strip().split('|') if x.find("timestamp") > -1 or x.find("head1") > -1 or x.find("head3") > -1) for l in fh])