【问题标题】:How to compare items in a group with pandas return boolean?如何将组中的项目与熊猫返回布尔值进行比较?
【发布时间】:2018-04-07 00:40:33
【问题描述】:

每个组'ID' 的第一行有一个end_date,我正在尝试识别组内的任何行,它们的begin_date 等于第一行的end_date。我需要为与日期匹配的行返回type。如果有多个匹配项,第一个就足够了。如果没有匹配项,则返回“不存在”。

df

ID    color  begin_date    end_date     type
1     red    2017-01-01    2017-01-07   Professional
1     green  2017-01-05    2017-01-07   Aquatic
1     blue   2017-01-07    2017-01-15   Superhero
1     red    2017-01-11    2017-01-22   Chocolate
2     red    2017-02-22    2017-02-26   Professional
2     green  2017-02-26    2017-02-28   Aquatic
2     blue   2017-02-26    2017-02-28   Superhero
2     red    2017-02-27    2017-02-28   Chocolate
3     red    2017-03-11    2017-03-22   Chocolate


if df.groupby('ID')['begin_date'].first() == df.groupby('ID')['end_date'].any():
    return df.groupby('ID')['end_date'].any().to_dict()
else: 
    return 'non-existent'

最终结果

ID    type     
1     Superhero
2     Aquatic
3     non-existant

【问题讨论】:

  • 您的代码与您的逻辑状态不匹配。

标签: python pandas boolean pandas-groupby


【解决方案1】:

IIUC

df.groupby('ID').apply(lambda x :  df.loc[x['begin_date'].isin(x['end_date'].iloc[[0]]).idxmax(),'type'] if x['begin_date'].isin(x['end_date'].iloc[[0]]).any() else 'non-existent')
Out[23]: 
ID
1       Superhero
2         Aquatic
3    non-existent
dtype: object

【讨论】:

    【解决方案2】:

    这是另一种方式,使用groupby()nth()reindex()

    df.groupby('ID').apply(lambda x: x.loc[x.begin_date.eq(x.end_date.iloc[0]), 'type']).groupby('ID').nth(0).reindex(df['ID'].unique(),fill_value='non existant')
    
    ID
    1       Superhero
    2         Aquatic
    3    non existant
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 1970-01-01
      • 2020-06-04
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多