python - 数据框转字符串
问题描述
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
import pandas as pd
TESTDATA = StringIO(txt)
df = pd.read_csv(TESTDATA,names=['col1'])
在哪里
txt="The lion (Panthera leo) is a species in the family Felidae;it is a muscular, deep-chested cat with a short, rounded head, a reduced neck and round ears, and a hairy tuft at the end of its tail. The lion is sexually dimorphic; males are larger than females with a typical weight range of 150 to 250 kg (330 to 550 lb) for males and 120 to 182 kg (265 to 400 lb) for females. "
当我运行上面的代码时,我得到的输出为:
The lion (Panthera leo) is a species in the family Felidae;it is a muscular deep-chested cat with a short rounded head a reduced neck and round ears and a hairy tuft at the end of its tail
我得到 4 个不同的列,最后一列标记为 col1。但我想要的是包含完整数据的单列。如何实现?我想将 txt 数据转换为具有单列的数据框。
解决方案
当您使用pd.read_csv
默认分隔符读取数据时,如果您想通过不同的分隔符将其拆分或使用不在文件中的分隔符来忽略所有分隔符,则,
需要显式传递sep=';'
给pd.read_csv(TESTDATA, sep=';')
sep='###'
推荐阅读
- javascript - 使用 lodash 或 es6 编写一个函数,该函数接受具有深度嵌套属性的对象并返回一个仅具有选择属性的新对象
- liferay - 无法在 Liferay 7.2 中呈现自定义表单字段
- vaadin - Vaadin 对话框以编程方式调整大小
- android - 下载unity bin.Data assets
- postgresql - 关系数据库设计以表示同一表的行之间的相似性
- c# - Unity C#:渲染一组精灵?
- kframework - 我们如何使用 --pdf 标志来生成文档?
- javascript - 在特定范围值上隐藏标签
- amazon-elastic-beanstalk - ASP Net Core IdentityServer,生产环境中的“发行者无效”
- python - 改变 seaborn 散点图中不同数据的图例属性