Skip to content

Instantly share code, notes, and snippets.

@mattions
Created May 2, 2018 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattions/96371763ebc8ef10f47c4dca714f858e to your computer and use it in GitHub Desktop.
Save mattions/96371763ebc8ef10f47c4dca714f858e to your computer and use it in GitHub Desktop.
import pandas as pd
data = {"colA": [1, 2 , 3, 4, 5, 6, 7 ,8],
"colB": ["one", "two", "one", "two", "one", "two", "one", "two"]}
df = pd.DataFrame(data)
# Always use the pattern
# df.loc[<selector>, column_to_change] = value
# selector is usually df['a_column'] == "something"
# the column can be one or more.
df.loc[df['colB'] == "one", "colC"] = "new_value"
df.loc[df['colB'] == "two", "colC"] = "old_value"
# Note the old way was
# df[df['colB'] == "one"]]['colC'] = "value"
# This is wrong do not use it anymore
# Check this: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment