How to find the string that generates Pandas SettingWithCopyWarning?

I have a large block of code that at some point somewhere generates a parameter with an error warning in pandas ( this problem ).

I know how to fix this problem, but I can not find the line number! Is there a way to cancel the line number (other than brute force methods like debugging or multiple fingerprints)? The only output I get is below, which does not pop up on the stack to my code:

C:\Anaconda3\lib\site-packages\pandas\core\frame.py:2302: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame  **kwargs)
+13
source share
1 answer

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

This will throw an exception pointing to the line that raises SettingWithCopyError.

: , :

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)
+15

Source: https://habr.com/ru/post/1589386/


All Articles