2021-02-26

New column in pandas df based on array

Say I have a df like the one below.

    num value
0   1   229
1   2   203
2   3   244
3   4   243
4   5   230

And an array: array([ 2, 4]).

I would like to create a new column for binary variable, such that it is 1 when num is equal to the value in the array and 0 otherwise.

    num value binary
0   1   229   0
1   2   203   1
2   3   244   0
3   4   243   1
4   5   230   0

Wanted to use: df["binary"] = np.where(df["num"] == dtemp.num.unique(), 1, 0), where dtemp.num.unique() is the aforementioned array. But since the lengths of df and array are different - I get the "Lengths must match to compare" error.



from Recent Questions - Stack Overflow https://ift.tt/3syheX3
https://ift.tt/eA8V8J

No comments:

Post a Comment