title: How to calculate conditional percent change between rows in pandas?
body: <p>Here's my dataframe:</p>
  
  <pre><code>df = pd.DataFrame({'Period': ['1_Baseline', '1_Baseline', '1_Baseline', '2_Acute', '2_Acute', '2_Acute', '3_Chronic', '3_Chronic', '3_Chronic', '4_Discontinuation', '4_Discontinuation', '4_Discontinuation'],
                 'Subject': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
                 'Amount': [24, 52, 34, 95, 98, 54, 32, 20, 16, 52, 34, 95]})
  </code></pre>
  
  <p>I want to create a column that contains a percent change in Amount within each Subject, for each Period, relative to Baseline. So, for Baseline, it would show how much the Amount changes for subject 1 from Baseline to Acute, and from 1_Baseline to 3_Chronic, and from 1_Baseline to 4_Discontinuation. It would do the same thing for each subject.</p>
  
  <p>Here's what I tried:</p>
  
  <pre><code>df['pct_change'] = df.groupby(['Period'])['Amount'].pct_change()
  </code></pre>
  
  <p>But I get:</p>
  
  <pre><code>               Period  Subject  Amount  pct_change
  0          1_Baseline        1      24         NaN
  1          1_Baseline        2      52    1.166667
  2          1_Baseline        3      34   -0.346154
  3             2_Acute        1      95    1.794118
  4             2_Acute        2      98    0.031579
  5             2_Acute        3      54   -0.448980
  6           3_Chronic        1      32   -0.407407
  7           3_Chronic        2      20   -0.375000
  8           3_Chronic        3      16   -0.200000
  9   4_Discontinuation        1      52    2.250000
  10  4_Discontinuation        2      34   -0.346154
  11  4_Discontinuation        3      95    1.794118
  </code></pre>
  
  <p>The results are not calculated within each Period, and are not relative to each Subject's previous Amount.</p>
  
  <p>Expect Output:</p>
  
  <pre><code>               Period  Subject  Amount  pct_change
  0          1_Baseline        1      24         NaN
  1          1_Baseline        2      52         NaN
  2          1_Baseline        3      34         NaN
  3             2_Acute        1      95         2.958333333
  4             2_Acute        2      98         0.884615385
  5             2_Acute        3      54         0.588235294
  6           3_Chronic        1      32         0.333333333
  7           3_Chronic        2      20        -0.615384615
  8           3_Chronic        3      16        -0.529411765
  9   4_Discontinuation        1      52         1.166666667
  10  4_Discontinuation        2      34        -0.346153846
  11  4_Discontinuation        3      95         1.794117647
  </code></pre>