
我有一个 pandas 数据框,如下所示,其中详细说明了对某个区域的其他调用:
| commsdate | area | day0 incremental | day1 incremental | day2 incremental |
|---|---|---|---|---|
| 01/01/24 | sales | 43 | 36 | 29 |
| 01/01/24 | service | 85 | 74 | 66 |
| 02/01/24 | sales | 56 | 42 | 31 |
| 02/01/24 | service | 73 | 62 | 49 |
| 03/01/24 | sales | 48 | 32 | 24 |
| 03/01/24 | service | 67 | 58 | 46 |
我正在尝试按日期计算收到的电话数量,因此 1 月 1 日收到的销售电话将是该日期的 day0_incremental (43),1 月 2 日将是 1 月 2 日的 day0 加上 1 月 1 日的 day1 (36+) 56) 和 1 月 3 日将是 1 月 3 日的 day0 加上 1 月 2 日的 day1 加上 1 月 1 日的 day2 (48+42+29),产生以下数据框:
| CallDate | Sales | Service |
|---|---|---|
| 01/01/24 | 43 | 85 |
| 02/01/24 | 92 | 147 |
| 03/01/24 | 119 | 195 |
| 04/01/24 | 63 | 107 |
| 05/01/24 | 24 | 46 |
我已经成功地为第二个表创建了数据框的外壳,在区域列下没有值,但不知道接下来的步骤:
df['commsdate'] = pd.to_datetime(df['commsdate'], format='%d/%m/%y')
areaunique = df['area'].unique().tolist()
from datetime import timedelta
calldate = pd.date_range(start=min(df['commsdate']), end=max(df['commsdate'])+timedelta(days=6), freq='d')
data = {area: [] for area in areaunique}
dfnew = pd.dataframe(data)
dfnew['calldate'] = calldate
dfnew = dfnew.melt(id_vars=['calldate'], var_name='area')
dfnew = dfnew.pivot(index='calldate', columns='area', values='value')
dfnew = dfnew.reset_index()
dfnew = dfnew[['calldate'] + areaunique]
我已经开始编写 for 循环,但我只做到了这一点:
良精商城网店购物系统是一套能够适合不同类型商品、超强灵活的多功能在线商店系统,三级分销 PC+移动端+微网站,为您提供了一个完整的在线开店解决方案。良精网店购物系统除了拥有一般网上商店系统所具有的所有功能,还拥有着其它网店系统没有的许多超强功能。多种独创的技术使得系统能满足各行业广大用户的各种各样的需求,是一个经过完善设计并适用于各种服务器环境的高效、全新、快速和优秀的网上购物软件解决方案。
for i in range(1,len(areaunique)+1):
dfnew.columns(i) =正确答案
df['commsdate'] = pd.to_datetime(df['commsdate'], dayfirst=true)
tmp = df.pivot(index='commsdate', columns='area')
out = (tmp['day0 incremental']
.add(tmp['day1 incremental'].shift(freq='1d'), fill_value=0)
.add(tmp['day2 incremental'].shift(freq='2d'), fill_value=0)
.reset_index().rename_axis(columns=none)
)
或者,使用从 dayx … 字符串中提取的数字以编程方式使用 functools.reduce:
from functools import reduce
import re
reg = re.compile(r'day(\d+)')
df['commsdate'] = pd.to_datetime(df['commsdate'], dayfirst=true)
tmp = df.pivot(index='commsdate', columns='area')
out = reduce(lambda a,b: a.add(b, fill_value=0),
(tmp[d].shift(freq=f'{reg.search(d).group(1)}d') for d in
tmp.columns.get_level_values(0).unique())
).reset_index().rename_axis(columns=none)
输出:
CommsDate Sales Service 0 2024-01-01 43.0 85.0 1 2024-01-02 92.0 147.0 2 2024-01-03 119.0 195.0 3 2024-01-04 63.0 107.0 4 2024-01-05 24.0 46.0









