Creating an accessible dataframe from MP-API query results

I am trying to convert the resulting query into a pandas dataframe as shown below, but format of the resulting dataframe looks off with the field name for fields I queried being in the tuples on each row instead of a being the title for each column Is there a simple way to get a dataframe like the last picture I have attached programmatically?

thanks in advance,

docs = mpr.summary.search(elements=["B"], exclude_elements=["N","C","Li","Ca","Mg","Na","K","Rb","Cs","Fr","Be","Sr","Ba","Ra","H","O","P","F","Cl"]     
                           ,fields=["formula_pretty", "density", "volume", "symmetry","material_id"])

df = pd.DataFrame(docs)
display(df)

Result of the displayed dataframe:

I think Dataframe.from_records() should work.

Hey @tschaume ,I tried this and got the same result, do I need us use some of the method parameters or combine this with another method?

Hi @J0chin,

here’s one way to go about it. It probably isn’t the most efficient and @munrojm might have better suggestions.

from flatten_dict import flatten

flattened = [{
    k: v for k, v in flatten(doc.dict(), reducer="dot").items() if k != "fields_not_requested"
} for doc in docs]

DataFrame.from_records(flattened)

HTH

1 Like