我有以下数据框:
transaction_date gp
2017-01-17 3477.92
2017-01-18 5839.64
2017-01-19 5082.19
2017-01-20 5761.63
2017-01-21 6705.89
2017-01-22 9937.17
2017-01-23 9432.93
2017-01-24 7965.56
2017-01-25 8517.26
2017-01-26 8098.36
2017-01-27 8947.25
2017-01-28 8473.38
2017-01-29 11660.13
2017-01-30 10266.24
2017-01-31 4350.21
2017-02-01 10820.15
2017-02-02 8554.61
2017-02-03 10689.69
我需要按照transaction_date
列开始按周开始,例如2017-01-23到2017-01-30之间的所有交易,Jan-23
所以基本上我需要一个新专栏' first_day_week'这表示交易发生在一周的开始日。
答案 0 :(得分:3)
您可以使用.dt
方法
s = pd.Series(data={
'2017-01-17':3477.92,
'2017-01-18':5839.64,
'2017-01-19':5082.19,
'2017-01-20':5761.63,
'2017-01-21':6705.89,
'2017-01-22':9937.17,
'2017-01-23':9432.93,
'2017-01-24':7965.56,
'2017-01-25':8517.26,
'2017-01-26':8098.36,
'2017-01-27':8947.25,} )
transaction_date = pd.Series(pd.to_datetime(s.index))
start_of_week = transaction_date - pd.to_timedelta(transaction_date.dt.weekday, unit='D')
start_of_week
0 2017-01-16
1 2017-01-16
2 2017-01-16
3 2017-01-16
4 2017-01-16
5 2017-01-16
6 2017-01-23
7 2017-01-23
8 2017-01-23
9 2017-01-23
10 2017-01-23
这可以分配到周开始列
如果格式很重要,您可以添加
start_of_week = start_of_week.dt.strftime('%b-%d')
答案 1 :(得分:3)