【发布时间】:2019-05-05 16:44:46
【问题描述】:
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 数据转换为单列数据框。
【问题讨论】:
-
首先,你不需要带有if else的STRINGIO,我想如果你尝试
pd.compat.StringIO(),它会调整兼容性。检查一次。其次,在读取 csv 时放置分隔符,例如\t,它在文件中不存在,它将仅读取 1 列 -
@anky_91 我只是按照你说的做了,输出还是没有变化。
-
pd.read_csv(pd.compat.StringIO("""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."""), header=None,sep='\t')这对我有用 -
@anky_91 我尝试了其他方式的语法,因为我没有得到输出。谢谢你的帮助!!
标签: python pandas dataframe stringio