Python split unicode

210 views Asked by At

I have the following Unicode string:

{u'prices': [{u'ask': 1.05321, u'instrument': u'EUR_USD', u'bid': 1.05308, u'time': u'2016-12-30T02:53:26.928268Z'}]}

and would like to convert it to a Dataframe with this structure:

ask           1.05321          
instrument    EUR_USD
bid           1.05308
time          2016-12-30T02:53:26.928268Z

thanks in advance.

2

There are 2 answers

0
Psidom On BEST ANSWER

If you mean pandas data frame:

import pandas as pd

dd = {u'prices': [{u'ask': 1.05321, u'instrument': u'EUR_USD', u'bid': 1.05308, u'time': u'2016-12-30T02:53:26.928268Z'}]}

pd.Series(dd['prices'][0]).to_frame().reset_index()

#        index  0
#0         ask  1.05321
#1         bid  1.05308
#2  instrument  EUR_USD
#3        time  2016-12-30T02:53:26.928268Z

Or use json_normalize:

from pandas.io.json import json_normalize
json_normalize(dd['prices']).T.reset_index()

#        index        0
#0         ask  1.05321
#1         bid  1.05308
#2  instrument  EUR_USD
#3        time  2016-12-30T02:53:26.928268Z
0
kvivek On

You can use pandas module to solve this.

import pandas as pd

inp = {u'prices': [{u'ask': 1.05321, 
                    u'instrument': u'EUR_USD',
                    u'bid': 1.05308,
                    u'time': u'2016-12-30T02:53:26.928268Z'}]
      }.values()[0]

df = pd.DataFrame(inp)

for k,v in df.iteritems():
   print k, v[0]