I have a Pandas DataFrame with this column:
This is an extraction from a database in Mongo but I don’t know how to handle a column containing both [] and {}:
How can split this column into two columns?
Desired result:
Thanks for your help !
I have a Pandas DataFrame with this column:
This is an extraction from a database in Mongo but I don’t know how to handle a column containing both [] and {}:
How can split this column into two columns?
Desired result:
Thanks for your help !
4
Answers
You can create a list of dictionaries (instead of a list of lists with dictionaries), then a dataframe and join this to the original df.
pandas has a function to construct DF from dictionaries
import pandas as pd
gives:
Combine
explode
andjson_normalize
:Or, if you have only one dictionary per list:
Or usig
from_records
:Output:
Create a df out of your base data:
Each element in the df is a dictionary within a list. Isolate the dictionary within the list using the apply method and a lambda function to access the first element in the list (the dictionary).
Use .values() to retrieve the dictionary values (year and value) which will exist as an object with dtype dict_values.
The dytpe of dict_values is pretty limiting so wrap it in a list function to convert to a list so you can use slicing and inxdexing:
Use the apply method with a lambda function and index positions to retrieve the years and values respectively, assign these to their respective column names within a dictionary and pass this as an arguement into the pd.DataFrame class to create a new dataframe: