0

I'm iterating through a range from 2010 to 2018. I want to include the results in my api pull for each year as a separate column in my data frame. I'mnot sure how to name the column titles to do so.

I tried using "Population {i}" for the column name.

for i in range(2010,2019):
    # Census & gmaps API Keys
    from config import (api_key, gkey)
    c = Census(api_key, year=i)

    # Configure gmaps
    gmaps.configure(api_key=gkey)
    # Run Census Search to retrieve data on all zip codes (2013 ACS5 Census)
    # See: https://github.com/CommerceDataService/census-wrapper for library documentation
    # See: https://gist.github.com/afhaque/60558290d6efd892351c4b64e5c01e9b for labels
    census_data = c.acs5.get(("NAME", "B19013_001E", "B01003_001E", "B01002_001E",
                              "B19301_001E",
                              "B17001_002E"), {'for': 'place:*','in': 'state:51'})

    # Convert to DataFrame
    census_pd = pd.DataFrame(census_data)

    # Column Reordering
    census_pd = census_pd.rename(columns={"B01003_001E": "Population[i]",
                                          "B01002_001E": "Median Age [i]",
                                          "B19013_001E": "Household Income [i]",
                                          "B19301_001E": "Per Capita Income [i]",
                                          "B17001_002E": "Poverty Count [i]",
                                          "NAME": "Name", "place": "Place [i]"})

    # Add in Poverty Rate (Poverty Count / Population)
    #census_pd["Poverty Rate"] = 100 * \
    #    census_pd["Poverty Count"].astype(int) / census_pd["Population"].astype(int)

    # Final DataFrame
    #census_pd = census_pd[["City", "Population", "Median Age", "Household Income",
     #/                      "Per Capita Income", "Poverty Count", "Poverty Rate"]]

    # Visualize
    print(len(census_pd))
    print (i)
    census_pd.head()
    census_pd.to_csv("test2.csv", index=False)
wcarhart
  • 2,685
  • 1
  • 23
  • 44
  • unfortunately, your question is not entirely clear. `"mystring goes here {}".format(i)` places the variable `i` in the string. Is this what you're looking for? – G. Anderson Aug 30 '19 at 16:57

1 Answers1

0

To get the index of the for loop, use enumerate():

for loop_index, i in enumerate(range(2010,2019)):
    ...

If you're using Python 3.6+, you can use an f-string.

census_pd = census_pd.rename(columns={"B01003_001E": f"Population[{loop_index}]", ...})

If you're using an earlier version of Python, there are a variety of methods for string interpolation. Here's one possibility:

census_pd = census_pd.rename(columns={"B01003_001E": "Population[{}]".format(loop_index), ...})

Further reading: Is there a Python equivalent to Ruby's string interpolation?

wcarhart
  • 2,685
  • 1
  • 23
  • 44