1

I want to add "1" in each row for columns "Score" where the below statement is true,

import pandas as pd
import numpy as np


df = pd.read_csv(Path1 + 'Test.csv')
df.replace(np.nan, 0, inplace=True)
df[(df.Day7 >= 500)]

Sample Value

Output

3 Answers3

1

You are halfway there. Just use df.loc[mask, "Score"] = 1:

import numpy as np
import pandas as pd

df = pd.DataFrame({"Day7":np.random.rand(5)*1000,
                   "Score": np.random.rand(5)})
print(df)
df.loc[(df.Day7>=500), "Score"] = 1
print(df)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
f.wue
  • 837
  • 8
  • 15
1

Could you please try following.

df['score']=np.where(df['Day7']>=500,1,"")

Or as per OP's comment(adding @anky_91's enhanced solution here):

np.where((df['Day7']>=500)&(df['Day7']<1000),1,"")

When we print the value of df following will be the output.

    Cat          Day7    score
0   Advertisir   145    
1   Blogs        56 
2   Business     92 
3   Classfied    23 
4   Continuin    110    
5   Corporate    1974     1
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0
df = df.assign(Score=0)
df.Score = df.Day7 >= 500
jgoday
  • 2,768
  • 1
  • 18
  • 17