简体   繁体   中英

Django JSON file to Pandas Dataframe

I have a simple json in Django. I catch the file with this command data = request.body and i want to convert it to pandas datarame

JSON:

{ "username":"John", "subject":"i'm good boy", "country":"UK","age":25}

I already tried pandas read_json method and json.loads from json library but it didn't work.

I think you need DataFrame constructor:

json = { "username":"John", "subject":"i'm good boy", "country":"UK", "age":25 }
print (pd.DataFrame(json, index=[0]))
   age country       subject username
0   25      UK  i'm good boy     John

Or:

print (pd.DataFrame([json]))
   age country       subject username
0   25      UK  i'm good boy     John

EDIT:

If input is file and get error :

s = pd.read_json('file.json')

ValueError: If using all scalar values, you must pass an index

is necessary add typ=Series and then convert Series.to_frame with transpose by T :

s = pd.read_json('file.json', typ='series')
print (s)
age                   25
country               UK
subject     i'm good boy
username            John
dtype: object

df = s.to_frame().T
print (df)
  age country       subject username
0  25      UK  i'm good boy     John

You can also use pd.DataFrame.from_records() when you have json or dictonary

df = pd.DataFrame.from_records([ json ]) OR df = pd.DataFrame.from_records([ dict. ])

or

you need to provide iterables for pandas dataframe:

eg df = pd.DataFrame({'column_1':[ values ],'column_2':[ values ]})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM