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?
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.
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.
We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.
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.
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
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