Write value to column if row string contain column name

Question:

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:

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
Asked By: Shem

||

Answers:

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
Answered By: mozway

you can also use this

df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”

In your case

df.loc[ df["string"] == "b", "b"] = 1
Answered By: Abhishek Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.