1

I have a dataframe:

v1   v2  v3
x    b   x
o    x   x
x    x   x
b    b   b
g    b   g
x    g   x

I want to replace values in columns with 1 and 0. 1 if value is equal x (and type must be changed too), 0 if it anything else (and type must be changed too). How could i do that?

I try this, but it doesnt work:

for i in range(3):
    df.iloc[:,i].replace([0,1],['b','x'],inplace=True).astype("int")

And I don't know how to write part with 0 for anything besides of "x"

2 Answers 2

1

Quick (to write) and dirty using .applymap() on each element:

df.applymap(lambda el: 1 if el in ["x", "b"] else 0)

Vectorized method:

pd.DataFrame(df.isin(["x", "b"]), dtype="int", columns=df.columns)

Result

   v1  v2  v3
0   1   1   1
1   0   1   1
2   1   1   1
3   1   1   1
4   0   1   0
5   1   0   1

The dtypes are int64

Sign up to request clarification or add additional context in comments.

5 Comments

for the vectorized method, another approach is (df == "x").astype(np.int64)
Yeah if you don't need the column names, that is indeed the way to go.
Oops, I didn't realize the column names were reset. Thanks.
And if i want it be x and b i should write it this way pd.DataFrame(df.values == "x" or "b", dtype="int", columns=df.columns) ?
In that case, use df.isin(["x", "b"]). The answer is updated accordingly.
0

You can just do the following instead of an applymap -

(df=='x').astype(int)
    v1  v2  v3
0   1   0   1
1   0   1   1
2   1   1   1
3   0   0   0
4   0   0   0
5   1   0   1

If you want to check both 'x' and 'b', then use .isin() method -

(df.isin(('x','b'))).astype(int)
    v1  v2  v3
0   1   1   1
1   0   1   1
2   1   1   1
3   1   1   1
4   0   1   0
5   1   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.