3

Trying to convert the object type column of a dataframe into a list of dicts as it actually needs to be.

print df['A'].dtype
object

print df['A'][:1]
[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]

Is it possible to retrieve df['A'] as a list of dicts as dicts? Any help highly appreciated.

3
  • Can you add desired output? Commented Aug 31, 2016 at 5:58
  • Given an example of df['A'] Commented Aug 31, 2016 at 6:10
  • df['A'][:1] isn't iterable as a list and is of type 'str'. I want to change it to a list of dicts. for items in df['A'][:1]: print type(items) print items <type 'str'> [{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}] Commented Aug 31, 2016 at 6:15

1 Answer 1

3

use json

import json

df.A.apply(json.loads)

0    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
1    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
2    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
3    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
4    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
5    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
Name: A, dtype: object

Setup

df = pd.DataFrame([
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
    ],
    columns=['A'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.