1

I have a csv file that I turn into a json so that I can turn it into a panda data-frame.

Here is my code,

def create_png():

    f = open('sticks.csv', 'r')
    reader = csv.DictReader( f, fieldnames = ("xstk", "stk") )
    out = json.dumps( [row for row in reader ] )
    print out

    df = DataFrame([
        #TODO
    ])

The line 'print out' prints out "[{"xstk": "1", "stk": "0"}, {"xstk": "0", "stk": "1"}, {"xstk": "1", "stk": "0"}]"

So what can I put into #TODO to make the code run and turn this into a simple two column dataframe? I have looked at Create pandas dataframe from json objects but it is a complicated example.

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
Liam Pieri
  • 601
  • 1
  • 6
  • 19
  • 1
    Why not just read it directly in as a csv (using `pandas.read_csv`)? – Andy Hayden Mar 11 '14 at 23:48
  • Also, I updated my answer to that question you link to (it didn't really answer the headline question - how to read in json). Thanks for pointing that out. – Andy Hayden Mar 12 '14 at 00:10

1 Answers1

1

Simply read the string of the json in directly to read_json:

In [11]: pd.read_json('[{"xstk": "1", "stk": "0"}, {"xstk": "0", "stk": "1"}, {"xstk": "1", "stk": "0"}]')
Out[11]:
   stk  xstk
0    0     1
1    1     0
2    0     1

However, if you already have a csv you should really read it in directly using read_csv:

df = pd.read_csv('sticks.csv', names=["xstk", "stk"])
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535