簡體   English   中英

在 dataframe 中創建另一列以根據日期過濾掉月份中的星期幾

[英]make another column in dataframe to filter out the week of the month based on date

我有如下代碼:

from datetime import datetime
import random
pd.DataFrame({'date':pd.date_range(datetime.today(), periods=100).tolist(),
             'country': random.sample(range(1,101), 100),
             'amount': random.sample(range(1,101), 100),
             'others': random.sample(range(1,101), 100)})

我希望有一個 output 例如:

month_week sum(country) sum(amount) sum(other)
4_1
4_2
4_3
4_4

總和實際上是一周的價值總和。

像這樣的東西:

In [713]: df['month_week'] = df['date'].dt.month.map(str) + '_' + df['date'].apply(lambda d: (d.day-1) // 7 + 1).map(str)

In [725]: df.groupby('month_week').sum().reset_index()                                                                                                                                                      
Out[725]: 
   month_week  country  amount  others
0         4_3      377     367     290
1         4_4      315     445     475
2         4_5      128      48      47
3         5_1      395     355     293
4         5_2      382     500     430
5         5_3      286     196     250
6         5_4      291     448     343
7         5_5      151     147     109
8         6_1      434     359     437
9         6_2      371     301     487
10        6_3      303     475     243
11        6_4      327     270     274
12        6_5      174     114     161
13        7_1      432     253     360
14        7_2      272     321     361
15        7_3      353     404     327
16        7_4       59      47     163

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM