Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write value to column if row string contain column name

I have a dataframe which contains many pre-defined column names. One column of this dataframe contains the name of these columns.

I want to write the value 1 where the string name is equal to the column name.

For example, I have this current situation:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame(0,index=[0,1,2,3],columns = ["string","a","b","c","d"])
df["string"] = ["b", "b", "c", "a"]


string  a   b   c   d 
------------------------------
b       0   0   0   0
b       0   0   0   0
c       0   0   0   0
a       0   0   0   0

And this is what I would like the desired result to be like:


string  a   b   c   d 
------------------------------
b       0   1   0   0
b       0   1   0   0
c       0   0   1   0
a       1   0   0   0

>Solution :

You can use get_dummies on df['string'] and update the DataFrame in place:

df.update(pd.get_dummies(df['string']))

updated df:

  string  a  b  c  d
0      b  0  1  0  0
1      b  0  1  0  0
2      c  0  0  1  0
3      a  1  0  0  0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading