【问题标题】:How to create a DataFrame out of a list of strings with a varying amount of attributes per string如何从字符串列表中创建一个 DataFrame,每个字符串具有不同数量的属性
【发布时间】:2020-09-24 19:54:32
【问题描述】:

假设我有一个字符串列表,其中每个条目都有可变数量的“属性”,因此顺序可能不同。

str_list = ['id1 [first="jake" last="sully" hours="24"]',
            'id2 [first="bob" last="ross" job="painter" hours="11]']

如何将该列表转换为数据框,如果字符串缺少属性,则它在 df 中将只是空白?

DataFrame 看起来像这样(列顺序必须如下所示):

   id   first        job     last    hours
  id1    jake               sully       24 
  id2     bob    painter     ross       11

我知道对于 id,我可以在 '[' 上拆分字符串并获取第 0 个索引,所以这不是问题。 为了从字符串条目中获取属性项,我知道我可以使用

test_list = re.findall(r'"(.*?)"', str)

要获取值列表,但我将如何在每个条目中使用不同数量的“属性”/混乱顺序来实现我的总体目标?

【问题讨论】:

    标签: python regex pandas dataframe data-structures


    【解决方案1】:

    试试这个:

    import re
    import pandas as pd
    
    str_list = ['id1 [first="jake" last="sully" hours="24"]', 'id2 [first="bob" last="ross" job="painter" hours="11"]']
    
    res = []
    for item in str_list:
        current = {'id': re.findall('id\d+', item)[0]}
        for col in ['first', 'last', 'job', 'hours']:
            x = re.findall(f'{col}="(.*?)"', item)
            if x :
                current[col] = x[0]
                
        res.append(current)
    
    pd.DataFrame(res)
    

    输出:

        id first   last hours      job
    0  id1  jake  sully    24      NaN
    1  id2   bob   ross    11  painter
    

    【讨论】:

    • 有什么方法可以在不手动重新排序的情况下保持顺序?
    • 我们可以在创建数据框后重新排序列,dict是无序的
    • 你能解释一下current = {'id': re.findall('id\d+', item)[0]} 在做什么吗?还有x = re.findall(f'{col}="(.*?)"', item)
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    相关资源
    最近更新 更多