1

I need to create a binary matrix

Example Data in a pandas DataFrame

ID P
2  1
1  2
3  2
1  3
1  4
2  5
3  5

Using

A = pd.DataFrame(index=df.ID.values, columns=df.P.values, 
                       data=(df.P.values == df.P.values[:,None]).astype(int))

My current output

Current Output

Which is correct in terms of where the '1's' hit, but I just want to have the column / row numbers consolidated and the row numbers in order as in:

index 1 2 3 4 5 6 7
1     0 1 1 1 0 1 0
2     1 0 0 0 1 0 1
3     0 1 0 1 1 1 0

If that's not clear, feel free to question!

2 Answers 2

1

Use get_dumies with max:

df = pd.get_dummies(df.set_index('ID')['P'].astype(str)).max(level=0).sort_index()
print (df)
    1  2  3  4  5
ID               
1   0  1  1  1  0
2   1  0  0  0  1
3   0  1  0  0  1
Sign up to request clarification or add additional context in comments.

1 Comment

Worked a treat! Thanks @jezrael
0

You could try pivot_table function

df["value"]=1
pd.pivot_table(df, values="value", index=["ID"], columns="P", fill_value=0) 

Comments

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.