0

this is the code i have

import pandas as pd
population_data = pd.read_csv("pop_data.csv",index_col="State")
population_data = population_data.groupby("State")["population"].sum().reset_index()

now if i type

print(population_data["State"])

then this is the output

0     AK
1     AL
2     AR
3     AZ
4     CA
.
.
.
50    WY
Name: State, dtype: object

I'm looking for a simple for loop code to just print the word "AK" or "AL" etc as the title for each graph separately

1 Answers1

0

Try this, not sure if it works

import pandas as pd
population_data = pd.read_csv("pop_data.csv",index_col="State")
population_data = population_data.groupby("State")["population"].sum().reset_index()

Then add [0] to the end of the code

print(population_data["State"][0])

If you want to loop through the States:

states = []
for i in range(len(population_data["State"]))
     # Either this
     states.append(population_data["State"][i])
     # Or the code to make a graph and the title

Now you can access all the states by states[num] where the num is the index of the states, starting from 0

Kiwirafe
  • 574
  • 4
  • 12
  • thank you! what should i type if i wanted to make a for loop that would iterate through each State in the next line? – Ritika Rajiv Oct 13 '20 at 22:57
  • Do you mean that you want to loop through all the states? Already edited the code for the loop. – Kiwirafe Oct 13 '20 at 23:02
  • i'm trying to actually create a loop for a graph! i need each state to appear as a separate title on each graph, if you could help me with that – Ritika Rajiv Oct 13 '20 at 23:27
  • Do you want to appened them a list? Can you give a bit more details thanks. – Kiwirafe Oct 13 '20 at 23:48
  • so from your code i got the output AK AL AR AZ CA CO ... etc but i now need to create a code that will make each state a title for a graph for each different graph – Ritika Rajiv Oct 13 '20 at 23:49
  • I just updated my code, and you can access all the states by `states[num]` where the num is the index of the states, starting from 0 – Kiwirafe Oct 13 '20 at 23:51