Issue
I have the following pandas DataFrame (without the last column):
name day show-in-appointment previous-missed-appointments
0 Jack 2020/01/01 show 0
1 Jack 2020/01/02 no-show 0
2 Jill 2020/01/02 no-show 0
3 Jack 2020/01/03 show 1
4 Jill 2020/01/03 show 1
5 Jill 2020/01/04 no-show 1
6 Jack 2020/01/04 show 1
7 Jill 2020/01/05 show 2
8 jack 2020/01/06 no-show 1
9 jack 2020/01/07 show 2
I want to add the last column as the cumulative sum of no-show appointments (sum of previous no-shows for each person). for each person in the new column that is called (previous-missed-appointments), it should start from 0.
Here is the data for easier reproducibility:
df = pd.DataFrame(
data=np.asarray([
['Jack', 'Jack', 'Jill', 'Jack', 'Jill', 'Jill', 'Jack', 'Jill', 'jack', 'jack'],
[
'2020/01/01',
'2020/01/02',
'2020/01/02',
'2020/01/03',
'2020/01/03',
'2020/01/04',
'2020/01/04',
'2020/01/05',
'2020/01/06',
'2020/01/07',
],
['show', 'no-show', 'no-show', 'show', 'show', 'no-show', 'show', 'show', 'no-show', 'show'],
]).T,
columns=['name', 'day', 'show-in-appointment'],
)
I tried various combos of df.groupby
and df.agg(lambda x: cumsum(x))
to no avail.
Solution
import pandas as pd
df.name = df.name.str.capitalize()
df['order'] = df.index
df.day = pd.to_datetime(df.day)
df['noshow'] = df['show-in-appointment'].map({'show': 0, 'no-show': 1})
df = df.sort_values(by=['name', 'day'])
df['previous-missed-appointments'] = df.groupby('name').noshow.cumsum()
df.loc[df.noshow == 1, 'previous-missed-appointments'] -= 1
df = df.sort_values(by='order')
df = df.drop(columns=['noshow', 'order'])
Answered By - Filip
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.