Hello, I'm going to make an if statement by going around the value.
If the value is greater than or equal to 25 or less than 8, score 3
If it's 9<=x<=11 or 21<=x<=24, then 2,
The rest of the code was created to assign a zero.
for x in df['value']:
if (x >=25) or (x<=8):
df['score']=3
elif (9<=x<=11) or (21<=x<=24):
df['score']=2
else:
df['score']=0
But if you look at the result,
value score
29 0
27 0
26 0
27 0
25 0
... ... ... ... ...
15 0
22 0
17 0
20 0
14 0
It's all going to be zero. Can you tell me what the problem is? Or is there an easier way than the if statement?
python pandas
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import pandas as pd
>>> df = pd.DataFrame({ "value": [ 1,2,3,4,5,6,7,11,12,13,14,15,16,1 ] })
>>> df
value
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 11
8 12
9 13
10 14
11 15
12 16
13 1
>>> def get_score(v):
if v < 7:
score = 0
elif v < 14:
score = 1
elif v < 21:
score = 2
else:
score = 3
return score
>>> df["socre"] = df["value"].apply(lambda v: get_score(v))
>>> df
value socre
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
5 6 0
6 7 1
7 11 1
8 12 1
9 13 1
10 14 2
11 15 2
12 16 2
13 1 0
>>>
You can do it like this. In the code you asked, if df["score"] = 0
, all values in df["score"]
will be zero.
© 2024 OneMinuteCode. All rights reserved.