1

I would like to convert a dictionary of the form:

1: [' Ma','Ant','Man','io'] 2: [' Sc','Alb','Man'] 3: [' Sc','Alb','Sch','bre']

to a matrix where all the possible values are the columns and keys are indices. Each cell of the matrix should contain 1 if the corresponding value ( column header) is present in the key and 0 otherwise.

' Ma' 'Ant' 'Man' 'io' ' Sc','Alb','Sch','bre' 1: 1 1 1 1 0 0 0 0 2: 0 0 1 0 1 1 0 0 3: 0 0 0 0 1 1 1 1

I don't know from where to start and how to use pandas and Dataframe to get this done.

1 Answer 1

3

You can use pd.DataFrame.from_dict to load the dictionary, then use pd.get_dummies to get the 0/1 values:

d = {1: ['Ma','Ant','Man','io'], 2: ['Sc','Alb','Man'], 3: ['Sc','Alb','Sch','bre']}
df = pd.DataFrame.from_dict(d, orient='index')
df = pd.get_dummies(df, prefix='', prefix_sep='').astype(int)

The resulting output:

   Ma  Sc  Alb  Ant  Man  Sch  bre  io
1   1   0    0    1    1    0    0   1
2   0   1    1    0    1    0    0   0
3   0   1    1    0    0    1    1   0
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.