需要匹配具有适当值的列表,我能够匹配两个列表,但是这里涉及三个列表。
# **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
在主列表中可用,现在必须匹配List2
和
主列表中的List4
。如果不匹配,则需要具有NA
期望使用熊猫低于产量。
Area Content
munnar NA
ooty hill
coonoor hill
nilgri mount
wayanad NA
coorg NA
chera hill
hima mount
请帮助!!!
答案 0 :(得分:4)
只需在reindex
之后df1和df2之后进行concat
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
答案 1 :(得分:3)
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