Python 基于其他列的复杂计算

Python 基于其他列的复杂计算,python,pandas,Python,Pandas,我已经成功地为其他列创建了基于算术的新列,但是现在我有一个更具挑战性的需要,首先根据多个列的匹配选择元素,然后执行数学运算,并且语法有问题 ind_df_qtrly[10:16] ticker comp_name per_fisc_year per_type per_fisc_qtr per_end_date_x sales tot_revnu zacks_x_sector_desc zacks_m_ind_desc per_end_date_y mkt_

我已经成功地为其他列创建了基于算术的新列,但是现在我有一个更具挑战性的需要,首先根据多个列的匹配选择元素,然后执行数学运算,并且语法有问题

ind_df_qtrly[10:16]
ticker  comp_name   per_fisc_year   per_type    per_fisc_qtr    per_end_date_x  sales   tot_revnu   zacks_x_sector_desc zacks_m_ind_desc    per_end_date_y  mkt_val
562170  AVX AVX CORP    2007    Q   1   2006-06-30  366.408 366.408 Computer and Technology ELECTRONICS 2008-12-31  1353.95
562215  AVX AVX CORP    2007    Q   2   2006-09-30  374.648 374.648 Computer and Technology ELECTRONICS 2008-12-31  1353.95
562260  AVX AVX CORP    2007    Q   3   2006-12-31  378.088 378.088 Computer and Technology ELECTRONICS 2008-12-31  1353.95
562305  AVX AVX CORP    2007    Q   4   2007-03-31  379.351 379.351 Computer and Technology ELECTRONICS 2008-12-31  1353.95
562350  AVX AVX CORP    2008    Q   1   2007-06-30  383.158 383.158 Computer and Technology ELECTRONICS 2008-12-31  1353.95
562395  AVX AVX CORP    2008    Q   2   2007-09-30  400.706 400.706 Computer and Technology ELECTRONICS 2008-12-31  1353.95
我试图计算从2008年第二季度开始的“tot_revnu”列的12个月后的值,这意味着对于每个“股票”我需要在DF中创建一个新列,该列将汇总四个季度(2008-Q2、2008-Q1、2007-Q4和2007-Q3)的结果。我用年度数据计算增长也做了同样的事情,但这项工作被证明是非常具有挑战性的

我可以用这样的年度数据来做这件事

        # Annual Create the Pivot Table
        ind_table=pd.pivot_table(ind_df_annual, values='tot_revnu',index=['ticker','comp_name','zacks_x_sector_desc','zacks_m_ind_desc','mkt_val'],columns=['per_fisc_year'],aggfunc=np.sum)

        # Annual calculate Simple and FD Growth and add columns to PivotTable
        ind_table[str(prev_year)+'-Ann Simple']= (ind_table[(prev_year)]  - ind_table[(prev2_year)])/ ind_table[(prev2_year)]
        ind_table[str(current_year)+'-Ann Simple']= (ind_table[current_year]  - ind_table[prev_year])/ ind_table[prev_year]
        ind_table[str(current_year)+'-Ann FD']= (ind_table[(str(current_year))+'-Ann Simple']  - ind_table[(str(prev_year))+'-Ann Simple'])/ ind_table[(str(prev_year))+'-Ann Simple']

你可以用一个滚动窗口。大概是这样的:

ind_df_qtrly['cumulative_tot_revnu'] = ind_df_qtrly['tot_revnu'].rolling(4).sum()

文档:

我也做了同样的事情,使用年度数据计算增长。。。这个尝试在哪里?你看过df.groupby吗?谢谢,我看过df.groupby,也看过df.pivot_表。我用另一个使用年度数据的数据集成功地做到了这一点。我会用这些信息更新问题,