Search code examples
python-3.xpandasdataframe

How can I split and add new row?


I have two rows:

  1.  [{'name': 'xxx', 'admin-status': 'up'}, {'name': 'zzz', 'admin-status': 'down'}]
  2.  {'name': 'yyy', 'admin-status': 'up'}

I want split row if it is list(first) row and add new row. result:

1. {'name': 'xxx', 'admin-status': 'up'}
2. {'name': 'zzz', 'admin-status': 'down'}
3. {'name': 'yyy', 'admin-status': 'up'}

DataFrame:


data = [
    "[{'name': 'xxx', 'admin-status': 'up'}, {'name': 'zzz', 'admin-status': 'down'}]",
    "{'name': 'yyy', 'admin-status': 'up'}"
]

df= pd.DataFrame(data,  columns=['data']))

I try chatgpt and other but I can not find solution.


Solution

  • Use ast.literal_eval to convert the strings to lists, with a custom function to ensure having a list, then explode:

    from ast import literal_eval
    
    def f(s):
        x = literal_eval(s)
        return x if isinstance(x, list) else [x]
    
    df['data'] = df['data'].map(f)
    
    out = df.explode('data')
    

    Output:

                                          data
    0    {'name': 'xxx', 'admin-status': 'up'}
    0  {'name': 'zzz', 'admin-status': 'down'}
    1    {'name': 'yyy', 'admin-status': 'up'}
    

    Alternatively, if you want to keep strings, you could strip the [] then split with a regex and explode:

    out = (df
       .assign(data=df['data'].str.strip('[]').str.split(', *(?={)'))
       .explode('data')
    )