【问题标题】:Create pandas df from raw text file从原始文本文件创建 pandas df
【发布时间】:2021-07-01 21:18:41
【问题描述】:

我有一个文本文件,我想将其格式化为 pandas 数据框。它被读取为以下形式的字符串:
print(text)=

product: 1
description: product 1 desc
rating: 7.8
review: product 1 review

product: 2
description: product 2 desc
rating: 4.5
review: product 2 review

product: 3
description: product 3 desc
rating: 8.5
review: product 3 review

我想我会通过使用 text.split('\n\n') 将它们分组到列表中来拆分它们。我会假设将每个迭代到一个 dict 中,然后加载到 pandas df 将是一个很好的路线,但我在这样做时遇到了麻烦。这是最好的路线吗,有人可以帮我把它变成熊猫 df 吗?

【问题讨论】:

    标签: python pandas list loops dictionary


    【解决方案1】:

    您可以将read_csv 与通过product 字符串和pivot 比较第一列来创建组一起使用:

    df = pd.read_csv('file.txt', header=None, sep=': ', engine='python')
    df = df.assign(g = df[0].eq('product').cumsum()).pivot('g',0,1)
    print (df)
    0      description product rating             review
    g                                                   
    1   product 1 desc       1    7.8   product 1 review
    2   product 2 desc       2    4.5   product 2 review
    3   product 3 desc       3    8.5   product 3 review
    

    或创建字典列表:

    #https://stackoverflow.com/a/18970794/2901002
    data = []
    current = {}
    with open('file.txt') as f:
        for line in f:
            pair = line.split(':', 1)
            if len(pair) == 2:
                if pair[0] == 'product' and current:
                    # start of a new block
                    data.append(current)
                    current = {}
                current[pair[0]] = pair[1].strip()
        if current:
            data.append(current)
            
    df = pd.DataFrame(data)
    print (df)
      product     description rating            review
    0       1  product 1 desc    7.8  product 1 review
    1       2  product 2 desc    4.5  product 2 review
    2       3  product 3 desc    8.5  product 3 review
    

    或者将每 4 个值重新整形为 2d numpy 数组并传递给 DataFrame 构造函数:

    df = pd.read_csv('file.txt', header=None, sep=': ', engine='python')
    
    df = pd.DataFrame(df[1].to_numpy().reshape(-1, 4), columns=df[0].iloc[:4].tolist())
    print (df)
      product     description rating            review
    0       1  product 1 desc    7.8  product 1 review
    1       2  product 2 desc    4.5  product 2 review
    2       3  product 3 desc    8.5  product 3 review
    

    【讨论】:

    • 前最后一个方法在我的数据样本集上效果很好。我问了一个简化版本,试图理解这个概念,我的庞大数据集在进行某些调整后遇到了错误。 ParserError: Expected 2 fields in line 568502, saw 3. Error could possibly be due to quotes being ignored when a multi-char delimiter is used. 我无法弄清楚到底是什么问题。有什么想法可以解决这个错误吗?
    • @rfl1735 - 可以检查行568502 吗?如果引用有问题,也许可以帮助df = pd.read_csv('file.txt', header=None, sep=': ', engine='python', quoting=3)
    • 使用quoting=3 得到错误ParserError: Expected 2 fields in line 568502, saw 3. 同样的错误,只是没有Error could possibly be due to quotes... 第568502 行是'review/text: 虽然,我们不会盲目品尝到Mozzarella 的想法对于这些,味道仍然很俗气,很好。我家里的每个人都喜欢这些。一种清淡的味道,让我们都为最后一口而奋斗。肯定会在杂货清单上。我现在添加了外部引号。
    • @rfl1735 - 我认为双 : 存在问题,因此 pandas 错误地将其拆分为 3 列。可能的解决方案是使用this 分割第一个:
    • 我很困惑,因为我在该行中只看到一个: 。你在哪里看到另一个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2021-05-25
    • 1970-01-01
    • 2013-08-07
    • 2019-11-07
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多