PHP前端开发

与pandas有条件合并

百变鹏仔 2个月前 (01-18) #Python
文章标签 有条件
问题内容

我有一个 pandas 数据框,如下所示,其中详细说明了对某个区域的其他调用:

commsdateareaday0 incrementalday1 incrementalday2 incremental
01/01/24sales433629
01/01/24service857466
02/01/24sales564231
02/01/24service736249
03/01/24sales483224
03/01/24service675846

我正在尝试按日期计算收到的电话数量,因此 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),产生以下数据框:

CallDateSalesService
01/01/244385
02/01/2492147
03/01/24119195
04/01/2463107
05/01/242446

我已经成功地为第二个表创建了数据框的外壳,在区域列下没有值,但不知道接下来的步骤:

df['commsdate'] = pd.to_datetime(df['commsdate'], format='%d/%m/%y')areaunique = df['area'].unique().tolist()from datetime import timedeltacalldate = 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'] = calldatedfnew = 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 循环,但我只做到了这一点:

for i in range(1,len(areaunique)+1):    dfnew.columns(i) =

正确答案


您可以拨打pivot、shift和add:

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 reduceimport rereg = 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  Service0 2024-01-01   43.0     85.01 2024-01-02   92.0    147.02 2024-01-03  119.0    195.03 2024-01-04   63.0    107.04 2024-01-05   24.0     46.0