如何找到生成 Pandas SettingWithCopyWarning 的行? [英] How to find the line that is generating a Pandas SettingWithCopyWarning?

查看:103
本文介绍了如何找到生成 Pandas SettingWithCopyWarning 的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大块代码,在某个地方,在 Pandas 中生成带有复制警告的设置(这个问题).

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 can't find what line number it is! Is there a way to back out the line number (apart from brute force methods like debug-stepping or putting in multiple prints)? The only output I get is the below, which doesn't go up 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)

推荐答案

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

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

这将引发指向触发 SettingWithCopyError 的行的异常.

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)

这篇关于如何找到生成 Pandas SettingWithCopyWarning 的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆