I am getting a type error as "TypeError: string indices must be integers" in the following code.
import pandas as pd
import json
from pandas.io.json import json_normalize
full_json_df = pd.read_json('data/world_bank_projects.json')
json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
json_nor.groupby('name')['code'].count().sort_values(ascending=False).head(10)
Output:
TypeError
Traceback (most recent call last)
<ipython-input-28-9401e8bf5427> in <module>()
1 # Find the top 10 major project themes (using column 'mjtheme_namecode')
2
----> 3 json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
4 #json_nor.groupby('name')['code'].count().sort_values(ascending = False).head(10)
TypeError: string indices must be integers
You cannot access a value in a string using another string. To solve TypeError: string indices must be integers; we should reference our dictionary instead of “ele“. We can access elements in our dictionary using a string. This is because dictionary keys can be strings.
1 comment. String indices must be integers. This means that when you're accessing an iterable object like a string, you must do it using a numerical value. If you are accessing items from a dictionary, make sure that you are accessing the dictionary itself and not a key in the dictionary.
you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
A simple way to traverse datasets based on JSON API specification. Normalize is a lightweight javascript library with simple and powerful api.
According to pandas documentation, for data
argument of the method json_normalize
:
data : dict or list of dicts Unserialized JSON objects
In above, pd.read_json
returns dataframe
.
So, you can try converting dataframe
to dictionary
using .to_dict()
. There are various options for using to_dict() as well.
May be something like below:
json_normalize(full_json_df.to_dict(), ......)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With