Answers for "pandas set all values where condition"

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)
Posted by: Guest on December-15-2020
0

switch pandas dataframe values where condition is true

>>> df = pd.DataFrame([[1, 25], [4, 40], [7, 45]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])
>>> df
            max_speed  shield
cobra               1       25
viper               4       40
sidewinder          7       45

>>> df.loc[df['shield'] > 35] = 0
>>> df
            max_speed  shield
cobra               1      25
viper               4       0
sidewinder          7       0
Posted by: Guest on August-31-2021

Code answers related to "pandas set all values where condition"

Python Answers by Framework

Browse Popular Code Answers by Language