Python Forum
Join each list elements with string in other DF
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Join each list elements with string in other DF
#1
HI All,

I've sample of 2 DF's as below and want to join/vlookup for each elements inside the list in DF1 (col1) with col1 and take col2 value in DF2.

import pandas as pd

df1 = pd.DataFrame({'col1':[ ['A1','A2'], ['A1','A2','A3'], ['A4','A5'], ['A2','A5'] ]})
df2 = pd.DataFrame({'col1':['A1','A2','A3','A4','A5'],'col2':[1,2,3,4,5]})
Expected output will be like:
expected_result = pd.DataFrame({'col1':[ ['A1','A2'], ['A1','A2','A3'], ['A4','A5'], ['A2','A5'] ], 
                                'col3': [ [1,2],[1,2,3],[4,5],[2,5] ]})
In my current code, I'm using explode method to break the lists but the result is not same as I expected.

df1 = df1.explode('col1')
df1.set_index('col1', inplace=True)
df1['col1'] = df2.groupby('col1').col2.apply(list)
df1.reset_index(drop=True, inplace=True)
df1
Is it possible to get the same result like expected output? Really appreciate for any help or suggestions. Thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Formula with elements of list - If-condition regarding the lists elements lewielewis 2 2,738 May-08-2020, 01:41 PM
Last Post: nnk
  convert a list of string+bytes into a list of strings (python 3) pacscaloupsu 4 10,846 Mar-17-2020, 07:21 AM
Last Post: markfilan
  Python dictionary adds only the last elements of a list mahmoud899 1 2,474 Dec-13-2018, 06:30 PM
Last Post: ichabod801
  Index in Python list contains multiple elements.How to access each val and pass them Shameendra 1 2,410 Nov-30-2018, 05:41 PM
Last Post: wavic
  Checking the elements of a matrix with an elements of a list juniorcoder 11 5,876 Sep-17-2018, 03:02 PM
Last Post: gruntfutuk
  How do you change specific elements in a char array of string? JoeB 4 6,530 Oct-31-2017, 09:50 AM
Last Post: JoeB
  How can i convert a string to an array with elements type float 64 zoya2385 3 6,129 May-11-2017, 03:57 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020