Home > database >  PANDAS Save a list of values in a dataframe
PANDAS Save a list of values in a dataframe

Time:08-06

I have a dict of this way :

{'Keyword': 'Batteries', 'Cluster': 10, 'KW_list': ['batteries', 'lithium', 'ion', 'lithium ion', 'battery', 'ion batteries', 'energy', 'solid', 'anode', 'density']}

And I want to save it in a pandas data frame like this

Keyword          Cluster            KW_list
Batteries        10                 ['batteries', 'lithium', 'ion', 'lithium ion', 'battery', 'ion batteries', 'energy', 'solid', 'anode', 'density']

But I get this

batteries   10  batteries
batteries   10  lithium

How could I save the whole list?

CodePudding user response:

Try this,

pd.DataFrame(data.items()).set_index(0).T

0    Keyword Cluster                                            KW_list
1  Batteries      10  [batteries, lithium, ion, lithium ion, battery...
  • Create dataframe from dictionary
  • Set index as first column and Transpose the dataframe.

CodePudding user response:

just put KW_list in another list and use pd.DataFrame.from_dict()

This code should work for your case

pd.DataFrame.from_dict({'Keyword': 'Batteries', 'Cluster': 10, 'KW_list': [['batteries', 'lithium', 'ion', 'lithium ion', 'battery', 'ion batteries', 'energy', 'solid', 'anode', 'density']]})
  • Related