1

The Dataframe have three columns.

     Month    Machine  Number of Machine
    January  Machine 1                  1
  February   Machine 2                  1
  February   Machine 3                  1
      March  Machine 2                  2
      April  Machine 4                  1
        May  Machine 1                  1
       June  Machine 3                  1

I want to put into a dictionary in this format but I am not unsure on how to do it.

{('January', 'Machine 1'): 1, ('February', 'Machine 2'): 1, ('February', 'Machine 3'): 1, ('March', 'Machine 2'): 1, ('April', 'Machine 4'): 1, ('May', 'Machine 1'): 1, ('January', 'Machine 3'): 1}

Notice that there is a duplication of month.

3 Answers 3

1

You can set the index to the pair 'Month','Machine' and then use the to_dict method.

df.set_index(['Month','Machine']).to_dict()['Number of Machine']
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like this:

my_dict = {tuple(i[:-1]): i[-1] for i in data}

Comments

1

You can do this iteratively using a loop

import pandas as pd
import numpy as np
from collections import defaultdict

def gen_dict(in_df):
    refHash = defaultdict()
    
    for row in in_df.values:
        key = tuple(row[:-1])
        refHash[key] = row[-1]
        
    return refHash

hash_map = gen_dict(in_df)

Another way would be to use index

df_dict = df.set_index(['Month','Machine']).to_dict()['Number of Machine']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.