Python列表匹配适当的索引

2024-06-16 10:04:08 发布

您现在位置:Python中文网/ 问答频道 /正文

I need to match the lists with appropriate indexes alone. There are 5 lists, one will be main list. List1/List2 will be combined together same way List3/List4. List1/List3 index will be available in main_list. List2 / List4 need to match with appropriate index in main_list

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


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

List2 = ['hill', 'hill', 'hill']

List3 = ['nilgri', 'hima', 'ooty']

List4 = ['mount', 'mount', 'mount']

df = pd.DataFrame(dict(Area=main_list))
df1 = pd.DataFrame(
    list(zip(List1, List2)),
    columns=('Area', 'Content')
)

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

re = pd.concat([df, df1, df2], ignore_index=True, sort=False)

Output:

       Area Content   cont
0    munnar     NaN    NaN
1      ooty     NaN    NaN
2   coonoor     NaN    NaN
3    nilgri     NaN    NaN
4   wayanad     NaN    NaN
5     coorg     NaN    NaN
6     chera     NaN    NaN
7      hima     NaN    NaN
8      ooty    hill    NaN
9   coonoor    hill    NaN
10    chera    hill    NaN
11   nilgri     NaN  mount
12     hima     NaN  mount
13     ooty     NaN  mount

Expected Output:

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

Tags: mainareananlistmountlist2list1hill
1条回答
网友
1楼 · 发布于 2024-06-16 10:04:08

IIUCset_indexconcat之前

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

相关问题 更多 >