【问题标题】:Python DataFrame to only have one columnPython DataFrame 只有一列
【发布时间】:2019-10-25 03:46:02
【问题描述】:

我有以下已添加到 Python DataFrame 的文本内容:

                                                    0  1
0                                      Invoice Number   
1   Strahse Road 24                               ...   
2   Bahnhofstrasse 40                             ...  
3   Page 1 /                                      ...  2

我只对整个文本内容有一个列感兴趣。

下面是方法,我用来将文本内容添加到数据框:

import pandas as pd
import io

def textToDataFrame(textContent):
    return pd.read_fwf(io.StringIO(textContent), header=None, na_filter=False)

这就是我得到上述输出的方式:

dataframe = textToDataFrame(text)
print(dataframe)

我有点不确定我该怎么做,所以我只能得到一 (0) 列?列数可以动态变化,具体取决于textContent

【问题讨论】:

  • textContent到底是什么对象?
  • @Xukrao textContent 只是一个string

标签: python pandas dataframe


【解决方案1】:
import pandas as pd

textContent = """Computer enthusiasts and power users, ask on Super User.
Professional system and network administrators, ask on Server Fault.
Users of TeX, LaTeX, ConTeXt, and related typesetting systems, ask on TeX - LaTeX Stack Exchange.
Database administrators and professionals, ask on Database Administrators Stack Exchange.
SharePoint enthusiasts, ask on SharePoint Stack Exchange."""

df = pd.DataFrame(textContent.split("\n"))
print(df)

给出结果:

                                                   0
0  Computer enthusiasts and power users, ask on S...
1  Professional system and network administrators...
2  Users of TeX, LaTeX, ConTeXt, and related type...
3  Database administrators and professionals, ask...
4  SharePoint enthusiasts, ask on SharePoint Stac...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2018-03-09
    • 1970-01-01
    • 2020-04-16
    • 2017-11-14
    相关资源
    最近更新 更多