【问题标题】:How to select the previous row in a group with pandas?如何选择熊猫组中的上一行?
【发布时间】:2018-09-11 03:24:46
【问题描述】:

我需要选择组内discharge_locationReadmit 之前的行。然后将 ID 和 Discharge_location 设置为字典。

样本df

ID     admit     discharge    discharge_location   first
20     3-4-2018  3-6-2018     Home                 1
20     2-2-2018  2-6-2018     Home                 0
20     2-5-2018  2-23-2018    Readmit              0
30     1-2-2018  2-3-2018     Rehab                1
30     1-15-2018 1-18-2018    Readmit              0
30     1-20-2018 1-24-2018    Home                 0
40     1-20-2018 1-24-2018    Home                 0
40     1-20-2018 1-24-2018    Home                 0
40     1-20-2018 1-24-2018    Home                 0

最终结果

ID    Discharge_location
20    Home
30    Rehab

【问题讨论】:

    标签: python pandas dictionary pandas-groupby


    【解决方案1】:

    IIUC

    df.loc[df[df.discharge_location=='Readmit'].index-1]
    Out[1519]: 
       ID     admit discharge discharge_location  first
    1  20  2-2-2018  2-6-2018               Home      0
    3  30  1-2-2018  2-3-2018              Rehab      1
    

    来自MartyB

    df.loc[df[df.discharge_location=='Readmit'].index-1][['ID','discharge_location']].set_index('ID').to_dict()
    

    【讨论】:

    • 您理解正确。可以只选择身份证和出院地点吗?
    • 这是根据 Wen 的帮助的最终版本。 df.loc[df[df.discharge_location=='Readmit'].index-1][['ID','discharge_location']].set_index('ID').to_dict()
    • @MartyB 是的,也更新你自己的方法,谢谢:-)
    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2017-06-30
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多