Home > other >  How do I get a series with certain values based on a condition in a dataframe?
How do I get a series with certain values based on a condition in a dataframe?

Time:07-29

I've got a dataframe with a column like this:

data = {"col": [1, 3, 2, 0, 4, 2, 5, 0, 1, 3, 0]}
df = pd.DataFrame(data)

Out: 
    col
0     1
1     3
2     2
3     0
4     4
5     2
6     5
7     0
8     1
9     3
10    0

I want to get a Series the same length as that column, with 0's where the data in the column does not equal zero and 100 when it does like below. How do I go about this?

0       0
1       0
2       0
3     100
4       0
5       0
6       0
7     100
8       0
9       0
10    100

CodePudding user response:

Compare to 0 and multiply by 100, due to the False/0 and True/1 equivalence this will give 0/100:

df['col'].eq(0).mul(100)

output:

0       0
1       0
2       0
3     100
4       0
5       0
6       0
7     100
8       0
9       0
10    100
Name: col, dtype: int64

CodePudding user response:

You can use Numpy to Solve this :

import numpy as np
df['col'] = np.where(df['col'] > 0, 0, 100)

note : if value grater than 0 it return 0 else returns 100

  • Related