Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generating a dictionary from two columns of pandas dataframe and putting them into a new dataframe

This is my df:

import pandas as pd


df = pd.DataFrame(
    {
        'uri': ['a', 'a', 'a', 'b','b', 'c', 'c', 'c'],
        'predicate': ['same', 'wiki' ,'wiki', 'same', 'same', 'same', 'same', 'wiki'],
        'object': ['x', 'y' ,'s', 'h', 'k', 'o', 'm', 'n'],
    }
)

I want to generate a new dataframe like the one below:

uri    result
a      {'same':['x'], 'wiki':['y', 's']}
b      {'same':['h', 'k']}
c      {'same':['o', 'm'], 'wiki':['n']}

I tried this code but I don’t know how to generate a dataframe out of it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df.groupby(['uri', 'predicate'])['object'].apply(list).to_dict()

>Solution :

You can avoid double groupby by create list of tuples from MultiIndex Series:

s = df.groupby(['uri', 'predicate'])['object'].apply(list)

d = pd.DataFrame([(level, s.xs(level).to_dict()) for level in s.index.levels[0]],
                 columns=['uri','result'])
print (d)
  uri                               result
0   a  {'same': ['x'], 'wiki': ['y', 's']}
1   b                 {'same': ['h', 'k']}
2   c  {'same': ['o', 'm'], 'wiki': ['n']}
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading