Home > OS >  Python adding values to column base on conditions of another column
Python adding values to column base on conditions of another column

Time:09-21

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

CodePudding user response:

You can use .loc for that

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

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

  • Related