Home > Software engineering >  Write value to column if row string contain column name
Write value to column if row string contain column name

Time:08-24

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

CodePudding user response:

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

CodePudding user response:

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
  • Related