簡體   English   中英

Python匹配列表和適當的列表

[英]Python Match List with appropriate list

需要匹配具有適當值的列表,我能夠匹配兩個列表,但是這里涉及三個列表。

# **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屬於List2相同的List3屬於List4

我可以匹配List1List2List3List4使用列表理解

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

Area    Content
ooty    hill
coonoor hill
chera   hill

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


Area    Content
nilgri  mount
hima    mount

主列表中有List1List3 ,現在必須匹配Main List中的List2List4 如果不匹配,則需要使用熊貓在輸出下滿足NA Expecting。

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

請幫忙 !!!

只是不要reindex之后concat的DF1和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
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

​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM