代码之家  ›  专栏  ›  技术社区  ›  Sravee

根据条件比较熊猫数据帧行

  •  0
  • Sravee  · 技术社区  · 7 年前

    我有一个数据框架( df )如下:

    d = {'Item':['x','y','z','x','z'], 'Count' : ['10', '11', '12', '9','10'], 'Date' : pd.to_datetime(['2018-8-14', '2018-8-14', '2018-8-14', '2018-8-13','2018-8-13'])}
    
    df= pd.DataFrame(data=d)
    
    
    Item       Count        Date
    x          10           2018-08-14
    y          11           2018-08-14
    z          12           2018-08-14
    x          9            2018-08-13
    x          9            2018-08-12
    z          10           2018-08-13
    

    我要根据以下内容比较行: 对于每个项目,比较 max(Date) 具有 max(Date) - 1 .

    这意味着它应该比较项目的计数 x ,用于日期 2018-08-13 2018-08-14 . 如果数到 最大(日期) 大于此值,则应选择该行并将其存储在其他数据帧中。

    项目相同 z ,它应该比较日期的计数 2018年8月13日 2018年8月14日 因为计数更大,所以应该选择项的行 Z 计数 12 .

    输出: DF2

    Item     Count     Date
    x        10        2018-08-14
    z        12        2018-08-14
    

    我试过以下方法:

    if ((df.Item == df.Item) and
            (df.Date > df.Date) and (df.Count > df.Count)):
        print("we met the conditions!")
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   BENY    7 年前

    merge Item

    df.loc[df.reset_index().merge(df,on='Item').loc[lambda x : (x['Count_x']>x['Count_y'])&(x['Date_x']>x['Date_y'])]['index'].unique()]
    Out[49]: 
      Item  Count       Date
    0    x     10 2018-08-14
    2    z     12 2018-08-14
    
        2
  •  0
  •   Sravee    7 年前

    max(date) max(date)-1

    t_day = df[df.Date == df.Date.max()]
    y_day = df[df.Date == df.Date.max() - pd.to_timedelta(1, unit='d')]
    

    temp = t_day.merge(y_day, on = 'Item', how='outer')
    temp = temp.dropna()
    

    def func(row):
        if (int(row['Count_x']) > int(row['Count_y']) & (row['Date_x'] > row['Date_y'])):
            return '1'
        else:
            return '0'
    temp['cond'] = temp.apply(func, axis=1)
    

    temp.drop(['Count_y','Date_y','cond'],axis = 1, inplace=True)
    
    print(temp)
    

    Count_x      Date_x     Item   
    10         2018-08-14    x     
    12         2018-08-14    z