【发布时间】:2018-12-04 23:27:47
【问题描述】:
我有一个相对较大的数据框(约 1000 万行)。它有一个id 和DateTimeIndex。我必须在一段时间(上周\月\年)内为每一行计算具有一定id 的条目数。我使用relativedelta 创建了自己的函数,并将日期存储在单独的字典{id: [dates]} 中,但它的运行速度非常慢。我应该如何快速正确地做到这一点?
P.S.:我听说过pandas.rolling(),但我不知道如何正确使用它。
P.P.S.:我的功能:
def isinrange(date, listdate, delta):
date,listdate = datetime.datetime.strptime(date,format),datetime.datetime.strptime(listdate,format)
return date-delta<=listdate
主代码,包含大量不必要的操作:
dictionary = dict() #structure {id: [dates]}
for row in df.itertuples():#filling a dictionary
if row.id in dictionary:
dictionary[row.id].append(row.DateTimeIndex)
else:
dictionary[row.id] = [row.DateTimeIndex,]
week,month,year = relativedelta(days =7),relativedelta(months = 1),relativedelta(years = 1)#relative delta init
for row, i in zip(df.itertuples(),range(df.shape[0])):#iterating over dataframe
cnt1=cnt2=cnt3=0 #weekly,monthly, yearly - for each row
for date in dictionary[row.id]:#for each date with an id from row
index_date=row.DateTimeIndex
if date<=index_date: #if date from dictionary is lesser than from a row
if isinrange(index_date,date,year):
cnt1+=1
if isinrange(index_date,date,month):
cnt2+=1
if isinrange(index_date,date,week):
cnt3+=1
df.loc[[i,36],'Weekly'] = cnt1 #add values to a data frame
df.loc[[i,37],'Monthly'] = cnt2
df.loc[[i,38],'Yearly']=cnt3
示例:
id date
1 2015-05-19
1 2015-05-22
2 2018-02-21
2 2018-02-23
2 2018-02-27
预期结果:
id date last_week
1 2015-05-19 0
1 2015-05-22 1
2 2018-02-21 0
2 2018-02-23 1
2 2018-02-27 2
【问题讨论】:
-
请定义“上周”,例如这是否意味着一个月的最后 7 天?
-
你写的函数能不能也加一下?
标签: python pandas datetime dataframe pandas-groupby