title: How to find the mean of subseries in DataFrames?
body: <p>My personnel side project right now is to analyze GDP growth rates per capita. More specifically, I want to find the average growth rate for each decade since 1960, and then analyze it.</p>
  <p>I pulled data from the World Bank API(&quot;wbgapi&quot;)as a DataFrame:</p>
  <pre><code>import pandas as pd
  import wbgapi as wb
  gdp=wb.data.DataFrame('NY.GDP.PCAP.KD.ZG')
  gdp.head()
  </code></pre>
  <p>Output:
  <a href="https://i.stack.imgur.com/A1tE4.png" rel="nofollow noreferrer">gdp</a></p>
  <p>I then used nested for loops to calculate the mean for every decade and added it to a new dataframe.</p>
  <pre><code>row, col = gdp.shape
  meandata = pd.DataFrame(columns = ['Country', 'Decade', 'MeanGDP', 'Region'])
  
  for r in range (0, row, 1):
      countrydata = gdp.iloc[r]
      for c in range (0, col-9, 10):
          decade =  1960+c
          tenyeargdp = countrydata.array[c:c+10].mean()
          meandata  = meandata.append({'Country': gdp.iloc[r].name, 'Decade': decade, 'MeanGDP': tenyeargdp},  ignore_index=True)
          
      
  meandata.head(10)
  </code></pre>
  <p>The code works and generates the following output: <a href="https://i.stack.imgur.com/lewXI.png" rel="nofollow noreferrer">meandata</a></p>
  <p>However, I have a few questions about this step:</p>
  <ol>
  <li><p>Is there a more efficient way to do access the subseries of dataframes?  I read that &quot;for loops&quot;  should never be used for dataframes and that one should vectorize operations on dataframes?</p>
  </li>
  <li><p>Is the complexity O(n^2) since there are 2 for loops?</p>
  </li>
  </ol>
  <p>The second step is to group the individual countries by region, for future analysis. To do so I rely on the World Bank API which has its own <code>Region</code>, which each has a list of member economies/countries.</p>
  <p>I iterated through the regions and the member list of each region. If a <code>Country</code> is part of the <code>Region</code> list I added that region series.</p>
  <p>Since an economy/country can be part of multiple regions(ie the 'USA' can be part of <code>NA</code> and <code>HIC</code>(high-income country)), I concatenated the region to the previously added regions.</p>
  <pre><code>for rg in wb.region.list():
      for co in wb.region.members(rg['code']):
          str1 ='-'+meandata.loc[meandata['Country']==co, ['Region']].astype(str)        
          meandata.loc[meandata['Country']==co, ['Region']] = rg['code']+ str1        
  </code></pre>
  <p>The code works mostly, however, sometimes it gives the error message that <code>'meandata' is not defined</code>. I use Jupyter-Lab.</p>
  <p>Additionally, Is there a simpler/more efficient way of doing the second step?</p>
  <p>Thanks for reading and helping. Also, this is my first python/pandas coding experience, and as such general feedback is appreciated.</p>