CreamStat
CreamStat

Reputation: 2185

Pandas : Find last non-null value for each different value of a variable

I have a dataframe like this one:

    a1  l1
0   a   NaN
1   a   kl
2   a   NaN
3   a   NaN
4   a   er
5   b   ye
6   b   NaN
7   b   fk
8   b   NaN

What I want is, the last previous non-null value of l1 for each group of a1 values. So the expected output is:

    a1  l1  ex
0   a   NaN NaN
1   a   kl  NaN
2   a   NaN kl
3   a   NaN kl
4   a   er  kl
5   b   ye  NaN
6   b   NaN ye
7   b   fk  ye
8   b   NaN fk

I have tried to use shift but I don´t know how to skip missing values.

Upvotes: 1

Views: 1047

Answers (1)

cs95
cs95

Reputation: 402363

You'll need groupby and apply here:

df['ex'] = df.groupby('a1').l1.apply(lambda x: x.ffill().shift())
df

  a1   l1   ex
0  a  NaN  NaN
1  a   kl  NaN
2  a  NaN   kl
3  a  NaN   kl
4  a   er   kl
5  b   ye  NaN
6  b  NaN   ye
7  b   fk   ye
8  b  NaN   fk

Alternatively, chain two groupby calls in succession:

df['ex'] = df.groupby('a1').ffill().groupby('a1').shift()
df

  a1   l1   ex
0  a  NaN  NaN
1  a   kl  NaN
2  a  NaN   kl
3  a  NaN   kl
4  a   er   kl
5  b   ye  NaN
6  b  NaN   ye
7  b   fk   ye
8  b  NaN   fk

Upvotes: 2

Related Questions