1

Suppose now I have the following pandas data frame:

id text
1  A B C
2  B D
3  A D

And I want to get the following result:

id A B C D
1  1 1 1 0
2  0 1 0 1
3  1 0 0 1

I don't how to describe this transformation, it looks like one-hot encoding but they should be totally different.

Anyone knows how to do this transformation and what's the name of such transformation?

2 Answers 2

3

Something like str.get_dummies

pd.concat([df['id'],df.text.str.get_dummies(sep=' ')],1)
Out[249]: 
   id  A  B  C  D
0   1  1  1  1  0
1   2  0  1  0  1
2   3  1  0  0  1
Sign up to request clarification or add additional context in comments.

2 Comments

Nice use of get_dummies!
This version is better than mine. +1. My version is ignorant of sep parameter.
1

One way is via pd.get_dummies:

df = pd.DataFrame({'id': [1, 2, 3],
                   'text': ['A B C', 'B D', 'A D']})

df['text'] = df['text'].str.split(' ').str.join('|')

df = df.join(df['text'].str.get_dummies()).drop('text', 1)

#    id  A  B  C  D
# 0   1  1  1  1  0
# 1   2  0  1  0  1
# 2   3  1  0  0  1

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.