【问题标题】:Splitting data and label into two separate columns in a pandas dataframe将数据和标签拆分为熊猫数据框中的两个单独的列
【发布时间】:2017-08-12 23:44:25
【问题描述】:

我有一个包含如下行的文本文件:

一堆文字,有逗号、标点符号等,ham

该行总是以 ham 或 spam 结尾。如何读取包含此类数据的 csv 文件,并将文本的第一部分存储到“名称”字段中的最后一个逗号,并将最后一位存储为“标签”字段(在上述情况下,它将是:

  df["label"] = "ham", 
  df["name"] = 'A bunch of text, with commas, punctuations etc.' 

是否还有一种方法可以清除我上面描述的未指定的文本?假设某行末尾没有垃圾邮件或火腿,我想跳过那些。如何使用 pandas.read_csv() 来实现这一点?

【问题讨论】:

    标签: python string pandas dataframe split


    【解决方案1】:

    鉴于这是您的原始数据框:

    df
    
                                                    Col1
    0  A bunch of text, with commas, punctuations etc...
    1                                 test,foo,.bar,spam
    

    使用df.str.rsplit。在, 上拆分一次,并将结果展开为两列。 df.rename 将优雅地重命名您的列。

    df.Col1.str.rsplit(',', 1, expand=True).rename(columns={0 : 'name', 1 : 'label' })
    
                                                  name label
    0  A bunch of text, with commas, punctuations etc.   ham
    1                                    test,foo,.bar  spam
    

    【讨论】:

      【解决方案2】:

      您也可以在数据导入过程中执行此操作。您将需要使用正则表达式作为分隔符。该表达式正在寻找每行中最后一个逗号,后面跟着一些东西。以下应该作为一个体面的说明:

      import pandas as pd
      import io
      
      txt = u"A bunch of text, with commas, punctuations etc.,ham"
      
      with io.StringIO(txt) as f:
          df = pd.read_csv(f,
                           sep=",(?=[^,]+$)",
                           header=None,
                           engine="python",
                           names=['name', 'label']))
      
      print(df)
      

      应该让步:

                                                    name label
      0  A bunch of text, with commas, punctuations etc.   ham
      

      我希望这是有目的的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-18
        • 1970-01-01
        • 2019-04-21
        • 2018-12-04
        • 1970-01-01
        • 2021-10-11
        相关资源
        最近更新 更多