Pandas pct change from initial value
<p>I want to find the pct_change of <code>Dew_P Temp (C)</code> from the initial value of -3.9. I want the pct_change in a new column.</p>

<p>Source here:</p>

<pre><code>weather = pd.read_csv('https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv')
weather[weather.columns[:4]].head()


Date/Time        Temp (C)   Dew_P Temp (C)  Rel Hum (%)
0   2012-01-01   -1.8       -3.9             86
1   2012-01-01   -1.8       -3.7             87
2   2012-01-01   -1.8       -3.4             89
3   2012-01-01   -1.5       -3.2             88
4   2012-01-01   -1.5       -3.3             88
</code></pre>

<p>I have tried variations of this for loop (even going as far as adding an index shown here) but to no avail:</p>

<pre><code>for index, dew_point in weather['Dew_P Temp (C)'].iteritems():
    new = weather['Dew_P Temp (C)'][index]
    old = weather['Dew_P Temp (C)'][0]
    pct_diff = (new-old)/old*100
    weather['pct_diff'] = pct_diff
</code></pre>

<p>I think the problem is the <code>weather['pct_diff']</code>, it doesn't take the <code>new</code> it takes the last value of the data frame and subtracts it from <code>old</code> </p>

<p>So its always (2.1-3.9)/3.9*100 thus my percent change is always -46%.</p>

<p>The end result I want is this:</p>

<pre><code>Date/Time        Temp (C)   Dew_P Temp (C)  Rel Hum (%)   pct_diff
0   2012-01-01   -1.8       -3.9             86           0.00%
1   2012-01-01   -1.8       -3.7             87           5.12%
2   2012-01-01   -1.8       -3.4             89           12.82%  
</code></pre>

<p>Any ideas? Thanks!</p>

<p>You can use <code>iat</code> to access the scalar value (e.g. <code>iat[0]</code> accesses the first value in the series).</p>

<pre><code>df = weather
df['pct_diff'] = df['Dew_P Temp (C)'] / df['Dew_P Temp (C)'].iat[0] - 1
</code></pre>

python python-3.x pandas dataframe