1 回答
TA贡献1804条经验 获得超3个赞
虽然我没有亲自测试过这一点,但我相信您可以通过捕获警告并检查返回的捕获警告列表的长度来计算生成的警告数量。然后将其添加到数据框的当前形状:
import warnings
import pandas as pd
with warnings.catch_warnings(record=True) as warning_list:
someDataframe = pandas.read_csv(
filepath_or_buffer=our_filepath_here,
error_bad_lines=False,
warn_bad_lines=True
)
# May want to check if each warning object a pandas "bad line warning"
number_of_warned_lines = len(warning_list)
initialRowCount = len(someDataframe) + number_of_warned_lines
https://docs.python.org/3/library/warnings.html#warnings.catch_warnings
编辑:花了一点时间,但这似乎适用于 Pandas。我们将暂时重定向,而不是依赖内置警告stderr。然后我们可以计算该字符串中出现“Skipping Lines”的次数,并以带有此警告消息的坏行数结束!
import contextlib
import io
bad_data = io.StringIO("""
a,b,c,d
1,2,3,4
f,g,h,i,j,
l,m,n,o
p,q,r,s
7,8,9,10,11
""".lstrip())
new_stderr = io.StringIO()
with contextlib.redirect_stderr(new_stderr):
df = pd.read_csv(bad_data, error_bad_lines=False, warn_bad_lines=True)
n_warned_lines = new_stderr.getvalue().count("Skipping line")
print(n_warned_lines) # 2
添加回答
举报