简体   繁体   中英

Loops that produce different values for each item in list

I have a loop that goes through a list of countries in a list and I want to find the total from each one and put it as a new object with the country name. So I want a list at the end: australia_total, brazil_total, etc which has the total number for each country.

The last line in the code is the one that doesn't work

for c in countrylist:
  country = data[data.country == c]
  
  pivotcountry = country.pivot_table(['new_cases','new_deaths'], index='week', aggfunc='sum', margins=False)
  pivotcountry.reset_index(level=0, inplace=True)
  {c}_total = pivotcountry.new_cases.iloc[-1]

If you want the totals to appear in a new DataFrame then you'll need to add a new row for each time around the loop:

import pandas

data = pandas.read_csv(r"WHO-COVID-19-global-data.csv", skipinitialspace=True)

countrylist = data.Country.unique()

out_columns = ['Country', 'Total_cases', 'Total_deaths']
out_data = pandas.DataFrame(columns=out_columns)

for c in countrylist:
  country = data[data.Country == c]

  case_total = country['New_cases'].sum()
  deaths_total = country['New_deaths'].sum()
  out_data = out_data.append(pandas.DataFrame([[c, case_total, deaths_total]], columns=out_columns))

print(out_data)

Gives:

                               Country Total_cases Total_deaths
0                          Afghanistan       34451         1010
0                              Albania        3571           95
0                              Algeria       19195         1011
0                              Andorra         855           52
0                               Angola         506           26
..                                 ...         ...          ...
0   Venezuela (Bolivarian Republic of)        9178           85
0                             Viet Nam         372            0
0                                Yemen        1469          418
0                               Zambia        1895           42
0                             Zimbabwe         985           18

[216 rows x 3 columns]

But if you genuinely want a Python variable for each country, then you can use the locals() dictionary:

import pandas

data = pandas.read_csv(r"WHO-COVID-19-global-data.csv", skipinitialspace=True)

countrylist = data.Country.unique()

for c in countrylist:
  country = data[data.Country == c]

  case_total = country['New_cases'].sum()
  locals()['%s_total' % (c.lower())] = case_total

print("Australia: %s" % australia_total)
print("Germany: %s" % germany_total)

However I wouldn't recommend using locals() to set new variables as it's not obvious to someone reading the code that new variable names are being created without using the traditional foo = 123 assignment statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM