You can generalize this process by getting the cumsum of pd.get_dummies. This should work for an arbitrary number of objects you want to count, without needing to specify each one individually:
# Get the cumulative counts.
counts = pd.get_dummies(df['object']).cumsum()
# Rename the count columns as appropriate.
counts = counts.rename(columns=lambda col: col+'_count')
# Join the counts to the original df.
df = df.join(counts)
The resulting output:
time object obj1_count obj2_count
0 04:10 obj1 1 0
1 04:10 obj1 2 0
2 04:11 obj1 3 0
3 04:12 obj2 3 1
4 04:12 obj2 3 2
5 04:12 obj1 4 2
6 04:13 obj2 4 3
You can omit the rename
step if it's acceptable to use count as a prefix instead of a suffix, i.e. 'count_obj1'
instead of 'obj1_count'
. Simply use the prefix
parameter of pd.get_dummies
:
counts = pd.get_dummies(df['object'], prefix='count').cumsum()