I have written the following code that has a function model_data to perform a particular set of tasks. I have to pass the list of Badges and the type of category 1 or 2 along with an empty dataframe data.

But while running the code I am getting an error. I searched SO for answers but this type of Question was not found.


#Model Function

def model_data(badge_list, data):
  for key, value in badge_list.items():

    #Check for Post Type
    if (value == 1):
      badge_type = posts.loc[posts.PostTypeId == '1']

    elif (value == 2):
      badge_type = posts.loc[posts.PostTypeId == '2']

    #Obtain required fields from Badge Data 
    badge_type = badge_type[['OwnerUserId', 'Id','Score', 'CreationDate']]
    badge_type.columns = ['UserId', 'Id', 'Score','CreationDate']
    Badge = key
    #Obtain time when user first obtained Badge
    badge_data = user_badge_dt(Badge)

    #Find the number of posts made before and after 1 week of Badge Attainment
    post_data = post_details(df1 = badge_data, df2 = badge_type)
    post_data.date = pd.to_datetime(post_data.date)
    #Calculate APR
    post_data = APR(post_data)    
    #Calculate Score
    post_data = score(df = post_data, post_type = badge_type)
    #Generate Final Dataframe with Badge Count
    data1 = badge_number(post_data)
    data1 = data1[['1','2','3','date','Score','APR']]
    #Append Dataframe
    data = data.append(data1)
  return data

#Function Call
questionBadge_list = {'Good Question':1, 'Explainer':2}

data = pd.DataFrame()
badge1_data = model_data(badge_list = questionBadge_list, data = data)


IndexError: Too many levels: Index has only 1 level, not 2

ERROR LINE The code line badge_data = user_badge_dt(Badge) gives this error so I am adding the complete function.

#Function to obtain UserId with the date-time of obtaining given badge for the first time
def user_badge_dt(badge):
  #Creating DataFrame to obtain all UserId and date-Time of given badge
  df = badges[['UserId','Date']].loc[badges.Name == badge]
  #Obtaining the first date-time of badge attainment
  v = df.groupby("UserId", group_keys=False)['Date'].nsmallest(1)
  v.index = v.index.droplevel(1)

  df['date'] = df['UserId'].map(v)
  #Removing all duplicate values of Users
  df.drop_duplicates(subset='UserId',  inplace=True )

  return df

Badges DataFrame Sample

   Id UserId    Name            Date                   
0   2   23  Nice Answer     2016-01-12T18:44:49.267 
1   3   22  Autobiographer  2016-01-12T18:44:49.267 
2   4   21  Curious         2016-01-12T18:44:49.267 
3   5   20  Autobiographer  2016-01-12T18:44:49.267 
4   6   19  Autobiographer  2016-01-12T18:44:49.267 
  • $\begingroup$ where exactly does it fail? you only say it fails somewhere in your function user_badge_dt(). $\endgroup$ – N. Kiefer Sep 17 '20 at 15:21
  • $\begingroup$ @N.Kiefer I checked my code line by line and have found the issue, the code fails at v.index = v.index.droplevel(1) in the user_badge_dt function. It is because for some inputs of badge given to the function the code line v = df.groupby("UserId", group_keys=False)['Date'].nsmallest(1) includes index of dataframe df, but for some inputs it does not create index, thus the next line of droplevel(1) fails. I don't know why is this happening as all inputs have exactly the same format. $\endgroup$ – Ishan Dutta Sep 17 '20 at 15:24
  • $\begingroup$ This depends on the data you have apparently, and I can't see your data. It looks like your data has only one level of index, not more so there is nothing to drop. have you had a look here? this question btw is better suited for stackoverflow. $\endgroup$ – N. Kiefer Sep 17 '20 at 15:34
  • $\begingroup$ @N.Kiefer I have added the data being used. I had looked into the droplevel documentation but it did not help. And I had asked this on StackOverflow but did not get any response. $\endgroup$ – Ishan Dutta Sep 17 '20 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.