Home > Net >  Converting pandas column with list of items to dictionary
Converting pandas column with list of items to dictionary

Time:03-09

I have DataFrame column like this:

col1
[DEBUG=true, DEBUG1=true]
[key1=true, key2=true]

This output DataFrame I want like this:

col1
{"DEBUG":"true", "DEBUG1": "true"}
{"key1":"true", "key2":"true"}

How can I achieve this?

CodePudding user response:

Here's one approach:

df['col1'] = df['col1'].explode().str.split('=').groupby(level=0).agg(list).apply(dict)

or you could use a list comprehension:

df['col1'] = [dict(x.split('=') for x in lst) for lst in df['col1'].tolist()]

Output:

                                  col1
0  {'DEBUG': 'true', 'DEBUG1': 'true'}
1     {'key1': 'true', 'key2': 'true'}

CodePudding user response:

Split each value in list comprehension and convert to dictionary:

df['col1'] = df['col1'].apply(lambda x: dict(y.split('=') for y in x))

df['col1'] = [dict(y.split('=') for y in x) for x in df['col1']]
print (df)
                                  col1
0  {'DEBUG': 'true', 'DEBUG1': 'true'}
1     {'key1': 'true', 'key2': 'true'}
  • Related