Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn series of dictionaries into a DataFrame - Pandas

I am trying to convert a series of dictionaries into a dataframe

0      {'neg': 0.0, 'neu': 0.462, 'pos': 0.538}
1      {'neg': 0.0, 'neu': 0.609, 'pos': 0.391}
2      {'neg': 0.043, 'neu': 0.772, 'pos': 0.185}
3      {'neg': 0.035, 'neu': 0.765, 'pos': 0.2}
4      {'neg': 0.0, 'neu': 0.655, 'pos': 0.345}
5      {'neg': 0.0, 'neu': 0.631, 'pos': 0.369}

I want the resulting DataFrame to have each key be its own column.

neg   neu     pos
0.0.  0.462   0.538
0.0   0.609   0.391
..    ..      ..

How can I accomplish this with Pandas?

like image 267
Simon Avatar asked Aug 24 '17 23:08

Simon


People also ask

How do I make a pandas DataFrame from a list of dictionaries?

Use pd. DataFrame. from_dict() to transform a list of dictionaries to pandas DatFrame. This function is used to construct DataFrame from dict of array-like or dicts.

Can python dictionary will be converted into pandas series?

You can create a pandas series from a dictionary by passing the dictionary to the command: pandas. Series() . In this article, you will learn about the different methods of configuring the pandas. Series() command to make a pandas series from a dictionary followed by a few practical tips for using them.

Can I convert dictionary to DataFrame?

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.

Can we convert Series to DataFrame?

In pandas, converting a series to a DataFrame is a straightforward process. pandas uses the to_frame() method to easily convert a series into a data frame.


1 Answers

Given your Series, ser

ser
Out: 
0      {'neg': 0.0, 'neu': 0.462, 'pos': 0.538}
1      {'neg': 0.0, 'neu': 0.609, 'pos': 0.391}
2    {'neg': 0.043, 'neu': 0.772, 'pos': 0.185}
3      {'neg': 0.035, 'neu': 0.765, 'pos': 0.2}
4      {'neg': 0.0, 'neu': 0.655, 'pos': 0.345}
5      {'neg': 0.0, 'neu': 0.631, 'pos': 0.369}

You can convert the Series to a list and call the DataFrame constructor:

pd.DataFrame(ser.tolist())
Out: 
     neg    neu    pos
0  0.000  0.462  0.538
1  0.000  0.609  0.391
2  0.043  0.772  0.185
3  0.035  0.765  0.200
4  0.000  0.655  0.345
5  0.000  0.631  0.369

Or you can apply the pd.Series constructor to each row. apply will be flexible and return a DataFrame since each row is a Series now.

ser.apply(pd.Series)
Out: 
     neg    neu    pos
0  0.000  0.462  0.538
1  0.000  0.609  0.391
2  0.043  0.772  0.185
3  0.035  0.765  0.200
4  0.000  0.655  0.345
5  0.000  0.631  0.369
like image 74
ayhan Avatar answered Oct 13 '22 01:10

ayhan