HappyPy HappyPy - 6 months ago 118
Python Question

retrieve value in a column corresponding to the first occurrence of an element in another column in pandas - python

df=pd.DataFrame({'a':['x','x','y','y','y','z','y','y'],'b':np.random.randn(8)})

a b
0 x -0.2414
1 x 1.2214
2 y 0.3442
3 y -2.9492
4 y 0.1214
5 z 2.8102
6 y -1.3844
7 y -0.7363


What is the most efficient way to select the value in column
b
that corresponds to the first occurrence of a letter in column
a
that is different from the previous letter?
This is what I'm trying to achieve

a b
0 x -0.2414
2 y 0.3442
5 z 2.8102
6 y -1.3844

Answer
df[df['a'] != df['a'].shift(1)]
Out[22]: 
   a         b
0  x  0.564161
2  y  1.498050
5  z  0.080116
6  y  0.255031

Original dataframe I used:

df
Out[23]: 
   a         b
0  x  0.564161
1  x -1.153969
2  y  1.498050
3  y  0.067259
4  y -0.345102
5  z  0.080116
6  y  0.255031
7  y  0.345250
Comments