【问题标题】:DataFrame to String数据框转字符串
【发布时间】: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


【解决方案1】:

当您使用pd.read_csv 读取数据时,默认分隔符是逗号,,如果您想用不同的分隔符分割数据或使用不在文件中忽略所有分隔符,如sep='###'

【讨论】:

  • 或者您也可以将escapechar 添加到read_csv,例如pd.read_csv(TESTDATA,names=['col1'], escapechar=',')
  • Bu 使用 sep=';',我的形状为 (0,1)。我将输出作为单列,其中行不存在。
  • @frank Shape 仍然是 (0,1),没有显示任何行。
【解决方案2】:

但我想要的是包含完整数据的单列。如何实现?我想将 txt 数据转换为单列数据框。

from io import StringIO
import pandas as pd    
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. "


memory_file=StringIO(txt)
df =pd.read_csv(memory_file, sep=r'\n', header=None, engine='python', names=["cname"])
print(df)
print(df.size)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2022-08-17
    • 2020-10-28
    • 2020-06-01
    • 2022-01-13
    • 2019-04-16
    相关资源
    最近更新 更多