简体   繁体   中英

Python List match with appropriate index

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

IIUC set_index before concat

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM