python - pandas apply individual logic to group -


if have pandas data frame looks like:

day id  val 1-jan     -5 2-jan     -4 3-jan     3 1-jan   b   2 2-jan   b   1 3-jan   b   -5 

how can add new column where, rows same id, if val negative on 1-jan, rows "y" , "n" if not? this:

day id  val neg_on_jan_1 1-jan     -5  y 2-jan     -4  y 3-jan     3   y 1-jan   b   2   n 2-jan   b   1   n 3-jan   b   -5  n 

i've looked @ group , apply-lambda functions still feel i'm missing something. i'm starting out pandas, coming background in sql, please forgive me if brain still thinks in rows , oracle analytic functions :)

included map per @ami tavory's suggestion

gb = df.set_index(['day', 'id']).groupby(level='id') s = gb.val.transform(lambda s: s.loc['1-jan'].lt(0)).map({1: 'y', 0:'n'}) s  day    id 1-jan      y 2-jan      y 3-jan      y 1-jan  b     n 2-jan  b     n 3-jan  b     n name: val, dtype: object 

df.merge(s.to_frame('neg_on_jan_1').reset_index()) 

enter image description here


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -