【问题标题】:Python List match with appropriate indexPython List 与适当的索引匹配
【发布时间】:2018-12-24 06:15:20
【问题描述】:

我需要将列表与适当的索引单独匹配。有5个 列表,一个将是主列表。 List1/List2 将组合在一起 同样的方式 List3/List4。 List1/List3 索引将在 主列表。 List2 / List4 需要与适当的索引匹配 主列表

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)

输出:

       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

预期输出:

       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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC set_index 之前 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
    

    【讨论】:

    • 看起来第一列的标题已更改为“索引”。我们可以有所需的标题吗?
    • @selvamsamymuthu .reset_index()
    猜你喜欢
    • 2017-03-10
    • 2018-07-24
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    相关资源
    最近更新 更多