Read the keys and values from the columns of a dataframe in Python

Viewed 136

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.

1 Answers

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()
Related