9951 explained code solutions for 126 technologies


python-pandasHow to change values in a column based on condition


import pandas as pd

data = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

data.loc[data['Phone Price'] < 400, 'Phone Price'] = data['Phone Price'] + 25;ctrl + c
import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.loc[

locates rows based on filter and updates with given values

data['Phone Price'] < 400

filter to update column values on

'Phone Price'

column name to update values

data['Phone Price'] + 25

new value expression


Usage example

import pandas as pd

data = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

data.loc[data['Phone Price'] < 400, 'Phone Price'] = data['Phone Price']+25;

print(data)
output
  Phone  Phone Price
0   ip5          229
1   ip6          329
2   ip8          404
3   sms          405
4    xi          330