我有如下代码:
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)})
我希望输出如下:
month_week sum(country) sum(amount) sum(other)
4_1
4_2
4_3
4_4
总和实际上是星期的总和。
答案 0 :(得分:1)
类似这样的东西:
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