pandas conditionally change column value by row code example
Example 1: pandas update with condition
import pandas as pd
import numpy as np
df = pd.DataFrame({'value':np.arange(1000000)})
# Solution 1 - Fastest :
df['value'] = np.where(df['value'] > 20000, 0, df['value'])
# Solution 2:
df.loc[df['value'] > 20000, 'value'] = 0
# Solution 3:
df['value'] = df['value'].mask(df['value'] > 20000, 0)
# Solution 4 - Slowest, note that df.where applies where condition is wrong:
df['a'] = df.where(df.a <= 20000, 0)
Example 2: set value based on column
df.loc[df['c1'] == 'Value', 'c2'] = 10