Last active
October 2, 2024 09:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!