Reputation: 79
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.
Upvotes: 2
Views: 1072
Reputation: 316
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:
e.g. df = pd.DataFrame({'column_1':[ values ],'column_2':[ values ]})
Upvotes: 2
Reputation: 862601
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
Upvotes: 2