首页 > 解决方案 > 如何修复 IndexError:太多级别:索引只有 1 级,而不是 Python 中的 2 级

问题描述

我编写了以下代码,该代码具有model_data执行一组特定任务的功能。我必须传递类别的列表Badges和类型1 or 2以及一个空的数据框data

但是在运行代码时出现错误。我搜索了答案,但没有找到这种类型的问题。

代码

#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

错误 行代码行badge_data = user_badge_dt(Badge)给出了这个错误,所以我添加了完整的函数。

#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)
  df.drop(columns='Date',inplace=True)
  
  #Removing all duplicate values of Users
  df.drop_duplicates(subset='UserId',  inplace=True )

  return df

标签: pythonpython-3.xpandasdataframedictionary

解决方案


推荐阅读