selvam samymuthu
selvam samymuthu

Reputation: 63

Python Match List with appropriate list

Need to match the lists with appropriate value, i was able to match with two lists, but here involved three lists.

# **Main List**
main_list = ['munnar', 'ooty', 'coonoor', 'nilgri', 'wayanad', 'coorg', 'chera', 'hima']

# **List1**
List1 = ['ooty', 'coonoor', 'chera']

# **List2**
List2 = ['hill', 'hill', 'hill']

# **List3**
List3 = ['nilgri', 'hima']

# **List4**
List4 = ['mount', 'mount']

List1 belong to List2 same List3 belong to List4,

I can match List1 with List2 and List3 with List4 using list comprehension

pd.DataFrame(
    list(zip(List1, List2)),
    columns=('Area', 'Content')
)

Area    Content
ooty    hill
coonoor hill
chera   hill

And

pd.DataFrame(
    list(zip(List3, List4)),
    columns=('Area', 'Content')
)


Area    Content
nilgri  mount
hima    mount

List1 and List3 is available in Main List, now have to match List2 and List4 in Main List. if its not matching then it need to have NA Expecting below output using pandas.

Area    Content
munnar  NA
ooty    hill
coonoor hill
nilgri  mount
wayanad NA
coorg   NA
chera   hill
hima    mount

Please help !!!

Upvotes: 0

Views: 52

Answers (2)

piRSquared
piRSquared

Reputation: 294218

main_list = ['munnar', 'ooty', 'coonoor', 'nilgri', 'wayanad', 'coorg', 'chera', 'hima']

list1 = ['ooty', 'coonoor', 'chera']
list2 = ['hill', 'hill', 'hill']
list3 = ['nilgri', 'hima']
list4 = ['mount', 'mount']

df = pd.DataFrame(dict(Area=main_list))

df.assign(Content=df.Area.map(dict([*zip(list1, list2), *zip(list3, list4)])))


      Area Content
0   munnar     NaN
1     ooty    hill
2  coonoor    hill
3   nilgri   mount
4  wayanad     NaN
5    coorg     NaN
6    chera    hill
7     hima   mount

​

Upvotes: 3

BENY
BENY

Reputation: 323226

Just do reindex after concat the df1 and df2

df=pd.concat([df1,df2]).set_index('Area').reindex(mainlist).reset_index()
df
Out[91]: 
      Area Content
0   munnar     NaN
1     ooty    hill
2  coonoor    hill
3   nilgri   mount
4  wayanad     NaN
5    coorg     NaN
6    chera    hill
7     hima   mount

Upvotes: 4

Related Questions