【问题标题】:How to transfer the text output into dataframe如何将文本输出传输到数据框
【发布时间】:2018-05-20 01:03:45
【问题描述】:

我用漂亮的汤做了一些网页抓取,这是我得到的输出文本:

TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
....

如何将此结果保存到数据框中?

如何将此信息保存到 csv 文件中。

我需要 csv 文件来做进一步的分析吗?

【问题讨论】:

  • 这些词之间用空格隔开

标签: python csv dataframe web-scraping beautifulsoup


【解决方案1】:

试试这个代码:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA=StringIO("""
TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
    """)

df = pd.read_csv(TESTDATA, sep=" ",header=None)
df.to_csv('output.csv', sep=',')
print df

此代码将打印数据帧并生成output.csv 文件。

更新 1:

list_raw=[]
for i in TESTDATA:

    list_raw.append(i.split(' '))

df=pd.DataFrame(list_raw)
print df

如果它在for循环读取中。使用如上所示的代码进行数据帧转换。然后按照最初显示的代码进行 df 到 csv 的转换。

【讨论】:

  • 同时支持 Py2 和 Py3 在 Py2 导入下还需要 from __future__ import print_function 和 print(df) 而不是 print df
  • 是的,这是正确的,但我的输出文本来自 for 循环。那么如何将 for 循环的结果传递给 'StringIO()' 呢?
  • @RujunGuan 然后使用list 追加为行。
  • @RujunGuan 你有答案吗?如果有任何错误,请在评论中询问
  • 刚刚完成。现在已经解决了。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2023-03-16
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 2019-04-22
相关资源
最近更新 更多