Python adding values to column base on conditions of another column

Question:

df = pd.DataFrame([['KALLANG/WHAMPOA', '2 ROOM', '01 TO 03', 47.0, 'IMPROVED', 92000.0, 0],
 ['QUEENSTOWN', '2 ROOM', '01 TO 03', 45.0, 'STANDARD', 185000.0, 0],
 ['QUEENSTOWN', '2 ROOM', '01 TO 03', 45.0, 'STANDARD', 205500.0, 0],
 ['TOA PAYOH', '2 ROOM', '01 TO 03', 45.0, 'IMPROVED', 248000.0, 0],
 ['JURONG WEST', '2 ROOM', '01 TO 03', 44.0, 'MODEL A', 181000.0, 0]], columns=['town', 
'flat_type', 'storey_range', 'floor_area_sqm', 'flat_model', 'resale_price', 'Points'])

How can I add value to the column points based on a condition like "town"=="QUEENSTOWN. I am trying to do a complex ranking system.

df[(df['town'] == 'QUEENSTOWN')]['Points']+5

I tried this but it doesn’t update the main dataframe

Asked By: N_ote

||

Answers:

You can use .loc for that

df.loc[df['town'] == 'QUEENSTOWN', 'Points'] += 5

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html

Answered By: bitflip
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.