python - 如何修复 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
解决方案
推荐阅读
- python - 用于数据块中散景的循环
- excel - 索引匹配季度数据集中的日期
- python - 我在使用 Python 解析 XML 字符串时遇到问题
- node.js - node.js 中的 SAML 身份提供程序实现?
- node.js - 如何使用 azure sdk for node 安排推送通知
- java - 文件未找到异常,访问被拒绝,Java
- ios - 有没有办法清除 iOS 上个人热点的 DHCP 租约?
- mongodb - mongodb - 副本集创建错误:仲裁检查失败,因为没有足够的投票节点响应
- c++ - 等待串口数据并合并结果
- python - 是否有任何优雅的方法来定义具有 dtype 数组列的数据框?