2

I'm planning improve readability for non Pandas developers; I have the following working Python code using .loc:

new_value = 'stackoverflow'
s_query = 'nbc'
SUGGESTED = 'suggested'
QUERY = 'query'
df.loc[(df[QUERY] == s_query), [SUGGESTED]] = new_value

Also have an option to:

new_value = 'stackoverflow'
s_query = 'nbc'
SUGGESTED = 'suggested'
QUERY = 'query'
df[SUGGESTED] = df[SUGGESTED].mask(df[QUERY] == s_query, new_value)

In this case df[SUGGESTED] column will be updated with 'stackoverflow' value for the row(s) matching df[QUERY] == s_query. Wondering if there is other options in Pandas to achieve same results.

gogasca
  • 9,283
  • 6
  • 80
  • 125

1 Answers1

2

You can use pd.DataFrame.masks sister method pd.DataFrame.where, it makes the Falses nan and fills in with the second argument

df[SUGGESTED] = df[SUGGESTED].where(df[QUERY] != s_query, new_value)

Or

df.update(df[QUERY].eq(s_query).map({True: new_value}))
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • Is there a way to not modify the False values and just change the row which matches the condition with new_value? – gogasca Apr 04 '17 at 01:09
  • what I mean is that df[SUGGESTED] = np.where(df[QUERY] == s_query, new_value, np.nan) will update other rows with NaN, but Im just interested in updating one row. – gogasca Apr 04 '17 at 01:30