I have a dataframe with two columns: one for ID_number and one for week_number. It can look like this:
df1 = pd.DataFrame({'ID_number':[13, 13, 14, 14, 14, 15, 15,16], 'week_number':[1, 2, 1, 2, 3, 1, 4, 5]})
# ID_number week_number
#0 13 1
#1 13 2
#2 14 1
#3 14 2
#4 14 3
#5 15 1
#6 15 4
#7 16 5
I want to select for every different ID, those ID where the week value is 2 and 3 and then make a label for the data. If an ID does not have week 2 AND 3, I label it with a 1. Else, I label it with a 0.
For now, I came around with a rather non elegant solution, that works, but I am sure that there must be another way:
def check_courier_week(df, field, weeks):
weeks_not_provided = weeks
new_df = df
new_df['label'] = np.zeros(len(df))
for c in np.unique(df[field]):
tmp = df[df[field] == c]
if len(np.unique(tmp.week_number.isin(weeks_not_provided))) == 1 and np.unique(np.unique(tmp.week_number.isin(weeks_not_provided))) == False:
new_df['label'][df[field] == c] = 1
else:
new_df['label'][df[field] == c] = 0
return new_df
Any ideas on how could this be improved? I guess there might be a solution using groupby, but I cannot think how to implement it.
The resulting label sould be:
# ID_number week_number label
#0 13 1 0.0
#1 13 2 0.0
#2 14 1 0.0
#3 14 2 0.0
#4 14 3 0.0
#5 15 1 1.0
#6 15 4 1.0
#7 16 5 1.0
Thanks!