CodeGuy - 1 year ago 47

Python Question

I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?

For example, in R, I would do:

`list = ifelse(list > 0, 1, 0)`

Answer Source

You can return `boolean`

values and use `astype(int)`

to convert them to `1`

and `0`

.

```
print((df['A'] > 0).astype(int))
```

**Example:**

```
df = pd.DataFrame({'A': [1,-1,2,-2,3,-3]})
print(df)
A
0 1
1 -1
2 2
3 -2
4 3
5 -3
print((df['A'] > 0).astype(int))
0 1
1 0
2 1
3 0
4 1
5 0
```