0

I guess I am running into a beginner problem: -> I want to loop over an array and insert the the values into lines of code that are executed. For the attempt below I get "SyntaxError: can't assign to operator"

#Country-subsets (all countries in dataframe)
for s in country_filter:  
  s.lower() + '_immu_edu' = immu_edu.loc[immu_edu['CountryName'] == s]

Thanks for helping!

My expected output would be:

guinea_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Guinea"]
lao_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Lao PDR"]
bf_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Burkina Faso"]
us_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "United States"]
ge_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Germany"]
val_to_many
  • 377
  • 5
  • 20
  • _insert the the values into lines of code that are executed_ What do you mean? - Also what is your expected output? – B001ᛦ Jun 26 '19 at 12:16
  • What does it mean to 'insert values into lines of code that are executed'? Can you show what your expected output is>? – WiseDev Jun 26 '19 at 12:16
  • 1
    @B001ᛦ Lol, I love how we have an identical comment. – WiseDev Jun 26 '19 at 12:17
  • You need to store the result `s.lower() + '_immu_edu'` somewhere as it is a temporary (also known as an "rvalue" in some languages). You can't assign to it. – tehhowch Jun 26 '19 at 12:17
  • So if `s` is the string `"foo"`, you want to create a variable named `foo_immu_edu`? That kind of "dynamic variable creation" is almost never a good idea. Use a dict instead: `d[s.lower() + '_immu_edu'] = whatever` – Kevin Jun 26 '19 at 12:17
  • Ahhh alright, I think I get it. Will try the dict solution. – val_to_many Jun 26 '19 at 12:22
  • 1
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Thierry Lathuille Jun 26 '19 at 12:29

1 Answers1

0

Store your values in a dictionary and access using the keys:

my_dict = dict()
for s in country_filter:  
  my_dict[s.lower() + '_immu_edu'] = immu_edu.loc[immu_edu['CountryName'] == s]
Kshitij Saxena
  • 930
  • 8
  • 19