-1

I want to iterate over a list with variable names in order to use these variables as input for a function. I think, it is more clear, when I provide the code.

data_low_wind= data.loc[data['Windspeed']<=10]
...#(high_wind and W,S,E have similar characteristic and not important for the problem)
data_N = data.loc[(data['WindDirection'] > 315) & (data['WindDirection'] <= 45)]
...
weather_condition = ['low_wind','high_wind','N','W','S','E']


 for i in weather_condition:
     if len(data_i) != 0:
        Errormeasure_i=table_Errormeasure(data_i,park_size)

This code does not work yet, as the values of weather_condition are read as strings and are in this way not recognized as addition to the data_ command. My goal is that the for-loop yields the following:

if len(data_low_wind)!=0:
   Errormeasure_low_wind=table_Errormeasure(data_low_wind,park_size)
#(and for the other elements of the list accordingly)

Is this in general a good (acceptable) approach? I read, that it is in general undesireable to change variable names via a for loop. Another approach I did, was using map(lambda...), however this also didnt yield the desired result.

weather_condition = ['low_wind','high_wind','N','W','S','E']
data= map(lambda x: 'data_'+x,weather_condition)
print(data)
[output] <map object at 0x00000180929D2860>

I appreciate any help and clarification of my problem. (I hope, this question is not to much of a duplicate. The other questions did not solve my issue)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
jonasa
  • 59
  • 6
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Jul 02 '20 at 01:30

1 Answers1

2

You should use dictionaries.

wind_data = {
    'low_wind': data.loc[data['Windspeed']<=10],
    'N': data.loc[(data['WindDirection'] > 315) & (data['WindDirection'] <= 45)],
    ...
}
error_measures = {}

for key, value in wind_data.items():
     if len(value) != 0:
         error_measures[key] = table_Errormeasure(value, park_size)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • When I run exactly this code, I get an error `weather_condition not defind`. When I change this to `for i in error_measures:` I dont get any output (even when I put print(error_measures[i]) at the end). Would that be the correct command? – jonasa Jun 07 '19 at 09:33
  • Sorry, updated - you should be using the keys and values of the wind_data dict. – Daniel Roseman Jun 07 '19 at 09:59
  • Sorry for being unclear. But i am still new to python and not really familiar to dicts. I assumed that your `wind_data {'low_wind:...}` replaced my list `weather_condition['low_wind'...]` – jonasa Jun 07 '19 at 10:06
  • Yes it should have, I updated the comment and the answer. – Daniel Roseman Jun 07 '19 at 10:06