How to find the line that is generating a Pandas SettingWithCopyWarning?

前端 未结 1 1766
囚心锁ツ
囚心锁ツ 2020-12-25 10:25

I have a large block of code that is, at some point somewhere, generating a setting with copy warning in pandas (this problem).

I know how to fix the problem, but I

1条回答
  •  生来不讨喜
    2020-12-25 11:24

    Set pd.options.mode.chained_assignment = 'raise'

    This will throw an exception pointing to the line which triggers SettingWithCopyError.

    UPDATE: how to catch the error, and interrogate the stacktrace to get the actual offending lineno:

    import pandas as pd
    from inspect import currentframe, getframeinfo
    from pandas.core.common import SettingWithCopyError
    
    pd.options.mode.chained_assignment = 'raise'
    
    df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
    
    df2 = df[df['a'] == 2]
    
    try:
        df2['b'] = 'foo'
    except SettingWithCopyError:
        print('handling..')
        frameinfo = getframeinfo(currentframe())
        print(frameinfo.lineno)
    

    0 讨论(0)
提交回复
热议问题