I want to add a new boolean column to a DataFrame that indicates if the value of a given column is seen for the first time in the groupby group.
My DataFrame is like this:
UserID Value
0 1955 30
1 1955 40
2 1955 30
3 1956 30
4 1957 30
5 1957 50
6 1958 30
7 1958 50
8 1958 30
9 1958 30
I want to obtain this:
UserID Value IsNewValue
0 1955 30 True
1 1955 40 True
2 1955 30 False
3 1956 30 True
4 1957 30 True
5 1957 50 True
6 1958 30 True
7 1958 30 False
8 1958 30 False
9 1958 30 False
It is important to note that the dataset is already ordered by UserID and Timestamp (here not shown) and i cannot change this sorting.
I came up with this code that works albeit being extremely inefficient:
def is_new(group, col):
seen = []
ret = []
for i in range(len(group)):
ret.append(group[col].iloc[i] not in seen)
seen.append(group[col].iloc[i])
group[f'IsNew{col}'] = ret
return group
for col in ['ValueA', 'ValueB', 'ValueC']:
dataset = dataset.groupby('UserID').apply(lambda x: is_new(x, col))
I was wondering how to rewrite the code and make it more efficient, maybe using windowing functions of Pandas or some numpy feature.