Reputation: 37
I have a Dataframe which contains a range of values for classification. It looks something like this:
df = pd.DataFrame(columns=['Place','lower limit','upper limit'],data=[['NY',0,1000],['MS',1001,2000],['AL',2001,3000],['BS',3001,4000],['CL',4001,5000],['FL',5001,6000]])
df
I need to create a dictionary with place and range of values given by place,lower limit and upper limit respectively. Something like:
dictionary = dict({'NY':range(0,1000), 'MS':range(1001,2000)})
But, since my dataframe is really long, i cant do it by hand. How could i automate this process of creating a dictionary from information on the dataframe?
Sorry if this has been answered before but i looked everywhere and didnt find anything.
Note: The reason that i want a Dictionary is because im gonna have to classify a very long file afterwards and dictionaries are the fastest way to do it. Thanks in advance.
Upvotes: 1
Views: 281
Reputation: 150785
Just a dict creation from list comprehension:
{a:range(b,c) for a,b,c in zip(df['Place'], df['lower limit'], df['upper limit'])}
Upvotes: 1
Reputation: 36299
You can use df.to_dict
and a dict comprehension:
{k: range(v['lower limit'], v['upper limit'])
for k, v in df.set_index('Place').to_dict(orient='index').items()}
Upvotes: 2