I have a dataframe that looks like this:
ID phone_numbers
1 [{u'updated_at': u'2017-12-02 15:29:54', u'created_at': u'2017-12-0
2 15:29:54', u'sms': 0, u'number': u'1112223333', u'consumer_id':
12345, u'organization_id': 1, u'active': 1, u'deleted_at':
None, u'type': u'default', u'id': 1234}]
I want to take the phone_numbers column and flatten the information inside of it so I can query say the 'id' field.
When I try;
json_normalize(df.phone_numbers)
I get error:
AttributeError: 'str' object has no attribute 'itervalues'
I am not sure why this error is being produced and why I can not flatten this column.
EDIT:
originally JSON string being read from a response object(r.text):
https://docs.google.com/document/d/1Iq4PMcGXWx6O48sWqqYnZjG6UMSZoXfmN1WadQLkWYM/edit?usp=sharing
EDIT:
Converted a column I need to flatten into JSON through this command
a = df.phone_numbers.to_json()
{"0":[{"updated_at":"2018-04-12 12:24:04","created_at":"2018-04-12 12:24:04","sms":0,"number":"","consumer_id":123,"org_id":123,"active":1,"deleted_at":null,"type":"default","id":123}]}
Use list comprehension with flatenning and adding new element ID
to dictionary:
df = pd.DataFrame({'ID': [1, 2], 'phone_numbers': [[{'a': '2017', 'b': '2017', 'sms': 1},
{'a': '2018', 'b': '2017', 'sms': 2}],
[{'a': '2017', 'b': '2017', 'sms': 3}]]})
print (df)
ID phone_numbers
0 1 [{'a': '2017', 'b': '2017', 'sms': 1}, {'a': '...
1 2 [{'a': '2017', 'b': '2017', 'sms': 3}]
df = pd.DataFrame([dict(y, ID=i) for i, x in df.values.tolist() for y in x])
print (df)
ID a b sms
0 1 2017 2017 1
1 1 2018 2017 2
2 2 2017 2017 3
EDIT:
df = pd.DataFrame({'phone_numbers':{"0":[{"type":"default","id":123}]}})
df = pd.DataFrame([y for x in df['phone_numbers'].values.tolist() for y in x])
print (df)
id type
0 123 default
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With