代码之家  ›  专栏  ›  技术社区  ›  ViSa

无法在python中将文本转换为数据帧

  •  0
  • ViSa  · 技术社区  · 1 年前

    我正在尝试转换a text 进入a dataframe 使用Python。

    sample_text: 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'

    最终期望输出:

    enter image description here

    实现上述输出的步骤如下:

    1. 将文本拆分为多行,并将其分配给一个变量 :我试过使用 print() 处理此文本 formatted_text = print('This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34') 但不能指定为 print() 退货 NoneType ,所以我在这里遇到了一个错误。

    此步骤后的期望输出:

    This is 
    sample text
    
    Name|age
    --|--
    1.abc|45
    2.xyz|34
    
    1. 使用上面的 line break text 存储在a variable 以带分隔符的CSV格式读取 | 创建数据帧 :我一直在考虑将其作为 pd.read_csv(formatted_text,sep='|', skipinitialspace=True)

    此步骤后的期望输出:

    enter image description here

    我之前试着解释过 this 在SO帖子中出现了问题,但我想我没能很好地解释它,所以它被关闭了。我希望这次我能解释一下我的问题。这可能是一项愚蠢的任务,但我已经坚持了很长时间,如果能得到任何帮助,我将不胜感激。

    3 回复  |  直到 1 年前
        1
  •  2
  •   mozway    1 年前

    您可以先拆分行,再拆分列,然后将其馈送到 DataFrame 构造函数,可选 fillna 具有 '' :

    s = 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'
    df = pd.DataFrame([x.split('|') for x in s.split('\n')]).fillna('')
    

    或者,使用 Series str.split :

    df = pd.Series(s.splitlines()).str.split('|', expand=True).fillna('')
    

    输出:

                 0    1
    0     This is      
    1  sample text     
    2                  
    3         Name  age
    4           --   --
    5        1.abc   45
    6        2.xyz   34
    
        2
  •  1
  •   PaulS    1 年前

    一种可能的解决方案:

    text = 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'
    
    pd.read_csv(StringIO(text), lineterminator='\n', engine='c', header=None)
    

    输出:

                 0
    0     This is 
    1  sample text
    2     Name|age
    3        --|--
    4     1.abc|45
    5     2.xyz|34
    

    要拆分列,我们可以使用 str.split 之后 read_csv :

    (pd.read_csv(StringIO(text), lineterminator='\n', engine='c', header=None)[0]
     .str.split('|', expand=True))
    

    输出:

                 0     1
    0     This is   None
    1  sample text  None
    2         Name   age
    3           --    --
    4        1.abc    45
    5        2.xyz    34
    
        3
  •  1
  •   m-sarabi    1 年前

    我们可以把每一行分成 | 并从中创建一个数据帧:

    import pandas as pd
    
    text = 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'
    
    array = [line.split('|') if '|' in line else [line, ''] for line in text.splitlines()]
    
    df = pd.DataFrame(array)
    print(df)
    

    输出:

                 0    1
    0     This is      
    1  sample text     
    2                  
    3         Name  age
    4           --   --
    5        1.abc   45
    6        2.xyz   34