Skip to content

Instantly share code, notes, and snippets.

@notbanker
Last active October 2, 2024 09:02
Show Gist options
  • Save notbanker/2be3ed34539c86e22ffdd88fd95ad8bc to your computer and use it in GitHub Desktop.
Save notbanker/2be3ed34539c86e22ffdd88fd95ad8bc to your computer and use it in GitHub Desktop.
Context manager to temporarily pandas set chained assignment warning to None,'warn' or 'raise, then revert
import pandas as pd
class ChainedAssignent:
""" Context manager to temporarily set pandas chained assignment warning. Usage:
with ChainedAssignment():
blah
with ChainedAssignment('error'):
run my code and figure out which line causes the error!
"""
def __init__(self, chained = None):
acceptable = [ None, 'warn','raise']
assert chained in acceptable, "chained must be in " + str(acceptable)
self.swcw = chained
def __enter__( self ):
self.saved_swcw = pd.options.mode.chained_assignment
pd.options.mode.chained_assignment = self.swcw
return self
def __exit__(self, *args):
pd.options.mode.chained_assignment = self.saved_swcw
@microprediction
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment