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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…