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.
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"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.