I'm trying to append zeroes to product id's data which are not present for any particular date and my code takes lot of time to append zeroes. Looking for an alternate approach in pandas/numpy.
Here is the sample data:
rpt_date product_id total_views total_cart_adds total_order_unit total_gmv
30-07-2022 mp000000006243574 7 1 0 0
30-07-2022 mp000000006292285 1 0 0 0
30-07-2022 mp000000006294016 18 1 0 0
31-07-2022 mp000000006243574 8 2 0 0
31-07-2022 mp000000006292285 5 0 0 0
For Eg if data for product id 'mp000000006294016' is not present on 31 or any other day then it should append 0 for the respective columns
Below is my code
df_ans=pd.DataFrame()
for x in prod_df['product_id']:
df2=pd.DataFrame()
print(prod_df[prod_df['product_id']==x])
df2 = prod_df[prod_df['product_id']==x]
if df2.shape[0] == 1:
formatted_date1 = time.strptime(prod_df['rpt_date'][0], "%d-%m-%Y")
formatted_date2 = time.strptime('30-07-2022', "%d-%m-%Y")
if formatted_date1==formatted_date2:
df2.loc[-1] = ['31-07-2022', x, '0', '0','0','0'] # adding a row
df2.index = df2.index + 1 # shifting index
df2 = df2.sort_index()
else:
df2.loc[-1] = ['30-07-2022', x, '0', '0','0','0'] # adding a row
df2.index = df2.index + 1 # shifting index
df2 = df2.sort_index()
print(df2)
df_ans= pd.concat([df_ans,df2])
print("***************************************")