1

I have a variable (var) with ids I am interested in finding out the position of last occurrence of Z

I have tried to convert it to an array with their positions

    zf1=np.where(df2['Var']=="Z")

This will give me the result as

    (array([4,5,6,7,8,9,10,11,12,22,23,24,25],dtype=int64),)

My idea was to find the difference of these values and look for -1 - I use the index value of this -1 to add an id next to it

    np.diff(zf1)


    Var              ID
    A
    B
    C
    Z
    Z
    Z
    Z
    Z
    Z
    Z
    Z
    Z          1
    X
    X
    X
    X
    X
    X
    B
    A
    C
    Z
    Z
    Z
    Z           2

np.diff is not giving me -1. Is there any alternate method?

sshr
  • 145
  • 1
  • 10

1 Answers1

0

Get Index values

df2.index[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]

Filter df2

df2[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • Thank you.. but it is giving me the last 'Z' the position. I want both 12th and 25th positions from the above data. Currently it is returning 25 – sshr Aug 31 '16 at 17:00
  • Thank you.. It really helps !! – sshr Aug 31 '16 at 18:29