Skip to content

Instantly share code, notes, and snippets.

@JohnnyFang
Last active April 27, 2019 23:40
Show Gist options
  • Save JohnnyFang/f73e133f61ca4caa68a7991d8e0223a0 to your computer and use it in GitHub Desktop.
Save JohnnyFang/f73e133f61ca4caa68a7991d8e0223a0 to your computer and use it in GitHub Desktop.
flatten nested json data using pandas' json_normalize
column_names = ["restaurant.id", "restaurant.name", "restaurant.cuisines", "restaurant.location.city",
"restaurant.location.address", "restaurant.location.latitude",
"restaurant.location.longitude", "restaurant.user_rating.rating_text"]
new_col_names = ["id", "name", "cuisines", "city", "address", "latitude", "longitude", "rating_text"]
if 'restaurants' in el and len(el['restaurants']):
df = pd.concat([pd.DataFrame(json_normalize(restaurant)) for restaurant in el['restaurants']])
restaurants_df = df[[col for col in column_names]]
restaurants_df.rename(columns=dict(zip(column_names, new_col_names)), inplace=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment