Home > database >  pandas: How do I create a dictionary with two columns and add them to an existing dictionary column?
pandas: How do I create a dictionary with two columns and add them to an existing dictionary column?

Time:06-06

You need to create a dictionary with two columns as shown below and add values to the dictionary in the existing columns. The two columns may be separated by , and multiple values may be added.

How can this be handled to make this possible?

   site  url           urls
0  a, b  link1, link2  {e: link3}
1  c, d  link3, link4  {f: link4}

↓

   urls
0  {e: link3, a: link1, b: link2}
1  {f: link4, c: link3, d: link4}

CodePudding user response:

Let us try apply along columns axis:

df.apply(lambda r: {**r['urls'], **dict(zip(r['site'].split(', '), r['url'].split(', ')))}, axis=1).to_frame('urls')

                                         urls
0  {'e': 'link3', 'a': 'link1', 'b': 'link2'}
1  {'f': 'link4', 'c': 'link3', 'd': 'link4'}
  • Related