2017-02-13 56 views
2

例如,我有這樣一個數據幀:如何計算在熊貓登錄記錄時過去7天的登錄用戶?

import random 
import pandas as pd 
l = [] 
for day in range(30): 
    for userid in range(random.randint(5,30)): 
     l.append([day,userid]) 
df = pd.DataFrame(l, columns=['Day','UserID']) 

我想知道獨特的用戶在過去7天數的記錄的用戶。我現在使用這樣的代碼:

result = {} 
df.set_index('Day',inplace=True) 
for d in df.index.unique(): 
    result[d] = df[(df.index>=d-6) & (df.index<=d)].count() 
pd.DataFrame(result).T 

但我認爲我的代碼糟透了。你能幫我看看更優雅的方式嗎?比如pandas.rolling_sum或其他什麼?

回答

0

你是對的:rolling_sum就是這樣。我想接近它的方式,儘管它已經不是一個班輪:

# Generate random log data 'your' way 
import random 
import pandas as pd 
l = [] 
for day in range(30): 
    for userid in range(random.randint(5,30)): 
     l.append([day,userid]) 
df = pd.DataFrame(l, columns=['Day','UserID']) 

# Calculate desired statistics 
df = df.groupby("Day").count() #calculate daily log count (this command will make a Day colum your index by default too) 
df.columns = ["Daily count"] #rename column to make it more meaningful 
df["Weekly count"]=pd.rolling_sum(df["Daily count"],window=7,min_periods=1) #calculate weekly count of previous column 

這將產生你想要的結果:

 Daily count Weekly count 
Day       
0    16   16.0 
1    13   29.0 
2    19   48.0 
3    8   56.0 
4    22   78.0 
5    21   99.0 
6    18   117.0 
7    7   108.0 
8    12   107.0 
9    7   95.0 
10   17   104.0 
11   21   103.0 
12   22   104.0 
13   20   106.0 
14   19   118.0 
... 
+0

感謝您的答覆。但是你似乎錯過了一點:如果一個用戶39在第一天和第二天登錄,你會數他兩次,但我們只應該算一次。 – kingbase