我有以下DataFrame badges
。该列UserId
包含同一用户的多个条目。我想获得给定的Date
每UserId
一个的最小值BadgeName
。我创建了一个函数user_badge_dt
来执行相同的操作,但出现索引错误。需要注意的一点是,尽管所有用户的数据集都是相同的,但我仅对某些徽章而不是其他徽章得到此错误。我不知道为什么会这样。
徽章数据框的一部分
UserId BadgeName Date
0 23 Curious 2016-01-12T18:44:49.267
1 22 Autobiographer 2017-01-12T18:44:49.267
2 23 Curious 2018-01-12T18:44:49.267
3 20 Autobiographer 2019-01-12T18:44:49.267
4 22 Autobiographer 2020-01-12T18:44:49.267
5 30 Curious 2020-01-12T18:44:49.267
功能
#Function to obtain UserId with the date-time of obtaining given badge for the first time
def user_badge_dt(badge_name):
#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
错误
IndexError: Too many levels: Index has only 1 level, not 2
注意
在进一步检查时,我发现此行引起了错误v.index = v.index.droplevel(1)
这是因为前面的代码行针对不同的徽章名称给出了不同的结果:
案例1:当代码对于给定徽章正确运行
df = badges [['UserId','Date']]。loc [badges.Name =='Autobiographer']
v = df.groupby(“ UserId”,group_keys = False)['Date']。nsmallest(1)打印(v)
o / p:
1 22 2017-01-12T18:44:49.267
3 20 2019-01-12T18:44:49.267
(此输出具有index
,UserId
并且具有Date
给定徽章的最小值)
案例2:当代码无法正确使用给定徽章
df = badges [[['UserId','Date']]。loc [badges.Name =='Curious']
v = df.groupby(“ UserId”,group_keys = False)['Date']。nsmallest(1)打印(v)
o / p:
23 2016-01-12T18:44:49.267
30 2020-01-12T18:44:49.267
(此输出不具有index
这就是为什么代码在下一行失败的原因。我不知道它是如何发生的。)
该函数对任何输入的预期输出badge_name
应返回一个数据框,其中包含UserId
和以及Date
给定标志的最小值。如果我的功能不清楚,请提供新方法来实现此目的。
我无法模拟您的错误,但是我认为您的解决方案应该简化DataFrame.sort_values
-然后让所有最早的用户使用最少的日期:
badges['Date'] = pd.to_datetime(badges['Date'])
def user_badge_dt(badge_name):
#Creating DataFrame to obtain all UserId and date-Time of given badge
return (badges.loc[badges.BadgeName == badge_name, ['UserId','Date']]
.sort_values('Date')
.drop_duplicates(subset='UserId'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句