[英]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
,
我可以匹配List1
与List2
和List3
与List4
使用列表理解
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
主列表中有List1
和List3
,现在必须匹配Main List中的List2
和List4
。 如果不匹配,则需要使用熊猫在输出下满足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.