【问题标题】:Convert any file (Readable as Text File) to Excel Format (.xlsx) virtually then convert as dataframe -Python将任何文件(可读为文本文件)虚拟转换为 Excel 格式(.xlsx),然后转换为数据框-Python
【发布时间】:2021-06-11 10:38:26
【问题描述】:

我几乎完全完成了我的项目 - 一个将包含数千行的机器日志转换为列并通过 pandas 分析其中的多个数据的应用程序。

但我必须先手动打开机器日志文件并保存为 .xlsx,然后在应用程序中打开保存的 .xlsx 文件才能将其转换为数据帧。

有什么方法可以虚拟地在python中打开文件并转换为数据框?

或打开文件>然后转换为excel>然后转换为数据框?

我试过了:

def openanyfile():
    f = open("Machine.LOG", "r")
    print(f.read())
    data = pd.DataFrame(f)
    print(data)

已成功读取并打印文件,但在转换为 pd.DataFrame 时,结果为“Empty DataFrame”。

此处附上示例原始文件:https://drive.google.com/file/d/1M6BXpqn10MJCc5mUfg9dGCJKAz_05G3W/view?usp=sharing

它可以作为文本文件读取。

当打开到 MS Excel 时,它将创建 2 列,我通过 pd.read_excel 操作并转换为数据框。

谢谢。

【问题讨论】:

  • 我认为问题在于您的 xml 形式的数据。 Pandas 引入了一种方法read_xml,但它附带了 1.3.0 版本,目前还没有 pip 版本。你可以看看这个post,它展示了如何将xml解析为pandas
  • @99_m4n 谢谢你。我试试。。

标签: python excel pandas


【解决方案1】:

不确定您是否仍在寻找解决方案。一个建议:您可以使用 Python 标准库中的 xml.etree.ElementTree。使用您提供的文件,这似乎可行:

import xml.etree.ElementTree as ETree

with open('Machine.LOG', 'rt') as file:
    data = '<Root>' + file.read() + '</Root>'
df = pd.DataFrame.from_records([
        {item.tag: item.text for item in record}
        for record in ETree.fromstring(data)
     ])

该文件不包含全封闭标签,所以我不得不添加一些没有实际意义的人工标签&lt;Root&gt;

结果(print(df):

                     Timestamp  ... Value
0     FRI NOV 02 04:36:42 2018  ...   NaN
1     FRI NOV 02 04:36:42 2018  ...   NaN
2     FRI NOV 02 04:36:46 2018  ...   NaN
3     FRI NOV 02 04:37:53 2018  ...   NaN
4     FRI NOV 02 04:37:56 2018  ...   NaN
...                        ...  ...   ...
9069  TUE NOV 06 03:09:09 2018  ...   NaN
9070  TUE NOV 06 03:09:13 2018  ...   NaN
9071  TUE NOV 06 03:09:14 2018  ...   NaN
9072  TUE NOV 06 03:09:15 2018  ...   NaN
9073  TUE NOV 06 03:09:16 2018  ...   NaN

也许有帮助。

【讨论】:

  • 非常感谢。已经试过了,效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 2018-07-22
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
相关资源
最近更新 更多