简体   繁体   中英

Convert a Dataframe to Dictonary in Python

I have a .csv file with demand values written like this below, which I need to transform into a dictionary to use in a mathematical optimizer

The dataframe values look like this:

mesoregion service value 
0 Metropolitana_SP_ BAU 10000 
1 Metropolitana_SP_ VIP / Retention 3000 
2 Guarulhos BAU 5000 
3 Guarulhos VIP / Retention 1000

Whch i could convert to a dictionary using this command:

demand = demand.set_index (['mesoregion', 'service']). T.to_dict ('list')

It looks like this:

{('Metropolitana_de_SP', 'BAU'): [10000], ('Metropolitana_de_SP', 'VIP / Retencao'): [3000], ('Guarulhos', 'BAU'): [5000], ('Guarulhos', 'VIP / Retention'): [1000]}

However, I need it to look like this (not as a list, but as a value for that tuple):

{('Metropolitana_de_SP', 'BAU'): 10000, ('Metropolitana_de_SP', 'VIP / Retencao'): 3000, ('Guarulhos', 'BAU'): 5000, ('Guarulhos', 'VIP / Retencao') : 1000}

Does anyone know how to help?

Thank you very much

this would be my solution:

# create example dataframe    
demand = pd.DataFrame([["Metropolitana_de_SP", "BAU", 10000],
                       ["Metropolitana_de_SP", "VIP / Retencao", 3000]], columns=["mesoregion", "service", "num"])

Then: Transform pandas columns into a list and save to a new column. After this, transform the list to a tuple object.

demand["values_as_list"] = demand[["mesoregion", "service"]].values.tolist()
demand["values_as_tuple"] = demand["values_as_list"].apply(lambda x: tuple(x))

Finally create the dict:

demand_dict = demand.set_index(['num'])["values_as_tuple"].to_dict()
print(demand_dict)
# {10000: ('Metropolitana_de_SP', 'BAU'), 3000: ('Metropolitana_de_SP', 'VIP / Retencao')}

Thank you very much MarkusOdenthal, you're a pro. It worked.

I just changed this: demand_dict = demand.set_index(['num'])["values_as_tuple"].to_dict()

to this: demand_dict = demand.set_index(["values_as_tuple"])['num'].to_dict()

To get what I wanted.

{('Metropolitana_de_SP', 'BAU'): 10000, ('Metropolitana_de_SP', 'VIP/Retencao'): 3000, ('Guarulhos', 'BAU'): 5000, ('Guarulhos', 'VIP/Retencao'): 1000}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM