9

So I have some data in json format, here's a snippet:

"sell": [
           {
               "Rate": 0.001425,
               "Quantity": 537.27713514
           },
           {
               "Rate": 0.00142853,
               "Quantity": 6.59174681
           }
]

What's the easiest way to access Rate and Quantity so that I can plot it in Matplotlib? Do I have to flatten/normalize it, or create a for loop to generate an array, or can I use pandas or some other library to convert it into matplotlib friendly data automatically?

I know matplotlib can handle inputs in a few ways

plt.plot([1,2,3,4], [1,4,9,16])

plt.plot([1,1],[2,4],[3,9],[4,16])
0

1 Answer 1

25

The simpliest is DataFrame constructor with DataFrame.plot:

import pandas as pd

d = {"sell": [
           {
               "Rate": 0.001425,
               "Quantity": 537.27713514
           },
           {
               "Rate": 0.00142853,
               "Quantity": 6.59174681
           }
]}

df = pd.DataFrame(d['sell'])
print (df)
     Quantity      Rate
0  537.277135  0.001425
1    6.591747  0.001429

df.plot(x='Quantity', y='Rate')

EDIT:

Also is possible use read_json for DataFrame.

Sign up to request clarification or add additional context in comments.

5 Comments

Brilliant, I'm just getting acquainted with pandas and dataframes. For anybody else who reads this, be sure that you include: import pandas as pd
It depends of structure of json. If structure is simple, read_json works perfectly. If more complicated or nested, solution also works, but is necessary some transforming.
Thanks so much! What would format look like if I wanted to append a timestamp to my dataframe? df = pd.DataFrame(jsonsource["result"]["sell"],timestamp)
Do you need append scalar value to new column?
If yes, then need df['timestamp'] = timestamp

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.