1

I have a csv file that has two columns. One for the timeslot and one for the Energy. I put this file into pandas dataframe and I have attached the screenshot of this.Screenshot of datafrmae

Now I would like to have dictionary that has as the key values the entries from one column and as the values the entries from the other column. I tried all the options mentioned here Convert a Pandas DataFrame to a dictionary but it was not successfull. Here you can see my code and my tried. I indicated the desired dictionary:

import pyomo.environ as pyo
import pandas as pd


#Define the model

model = pyo.ConcreteModel()


#Define the sets

model.set_timeslots = pyo.RangeSet(0,95)



# Read the data for the parameters from a csv file
dataframe = pd.read_csv("C:/Users/energy.csv", sep =";")

dictionary_dict = dataframe.to_dict('dict')
dictionary_list = dataframe.to_dict('list')
dictionary_series = dataframe.to_dict('series')
dictionary_split = dataframe.to_dict('split')

desiredDictionary = {'t0':7696850, 't1':7765100 , 't2': 7833350}

Can you tell me how I can automatically create this desired dataframe? I'd appreciate every comment.

PeterBe
  • 700
  • 1
  • 17
  • 37

1 Answers1

1

Use:

d = dataframe.head(3).set_index('Timeslot')['Energy'].to_dict()

If need all values:

d1 = dataframe.set_index('Timeslot')['Energy'].to_dict()

EDIT:

If need 2 dimensional key - tuple use:

d = dataframe.head(3).set_index(['Timeslot', 'household'])['Energy'].to_dict

d1 = dataframe.set_index(['Timeslot', 'household'])['Energy'].to_dict()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks jezrael for your answer. Basically it works. Maybe one follow up question. What if I wanted to have a 2 dimensional key (in this case the dataframe should have 3 columns). How could I implement this – PeterBe Feb 19 '21 at 09:43
  • @PeterBe - How should looks dict? Do you need `dataframe.head(3).set_index('Timeslot').to_dict()` ? – jezrael Feb 19 '21 at 09:44
  • Yes basically your answer is correct for my case. I was just wondering if I had a csv file with 3 columns e.g. Timeslot, household, Energy and I would like to have a dictionary with the 2-dimensional key (timeslot, household): Energy. How would this look like – PeterBe Feb 19 '21 at 09:46
  • Is this possible to have a 2-dimensional key? – PeterBe Feb 19 '21 at 14:05
  • Cool, thanks jezrael for your help. I really appreciate it. I upvoted and accepted your answer. – PeterBe Feb 19 '21 at 15:07