0

I have DataFrame like below:

rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : ["1", "2", "1", "1", "2"],
                   "Date" : rng,
                   "kind" : ["active", "not_active", "active", "active", "not_active"],
                   "status" : ["b2", "b2", "g8", "g8", "v10"]})

And i need to create DataFrame which will show what was the status of the last active and the last not active agreement. Below I upload example of result:

enter image description here

1 Answer 1

1

If datetimes are sorted you can use DataFrame.pivot_table:

df = (df.pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
        .reset_index()
        .rename_axis(None, axis=1))

If not sure if sorted add DataFrame.sort_values:

df = (df.sort_values(['ID','Date'])
        .pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
        .reset_index()
        .rename_axis(None, axis=1))
print (df)
  ID active not_active
0  1     g8        NaN
1  2    NaN        v10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.