python - 如何使用假设库创建日期时间索引 pandas DataFrame?

标签 python pandas pytest python-hypothesis

我正在尝试使用 hypothesis 库创建一个 pandas DataFrame 用于代码测试,代码如下:

from hypothesis.extra.pandas import columns, data_frames
from hypothesis.extra.numpy import datetime64_dtypes

@given(data_frames(index=datetime64_dtypes(max_period='Y', min_period='s'),
                   columns=columns("A B C".split(), dtype=int)))

我收到的错误如下:

E           TypeError: 'numpy.dtype' object is not iterable

我怀疑这是因为当我为 index= 构造 DataFrame 时,我只传递了一个 datetime 元素而不是 例如,ps.Series 都是 datetime 类型。即使是这种情况(我不确定),我仍然不确定如何使用 hypothesis 库来实现我的目标。

谁能告诉我代码有什么问题以及解决方案是什么?

最佳答案

出现上述错误的原因是,data_frames需要一个包含 strategy 元素的索引,例如 indexes对于 index= 输入。相反,上面的 datetime64_dtypes 只提供了一个 strategy 元素,但没有索引格式。

为了解决这个问题,我们首先提供索引,然后在索引中提供策略元素,如下所示:

from hypothesis import given, strategies 
@given(data_frames(index=indexes(strategies.datetimes()),
                   columns=columns("A B C".split(), dtype=int)))

请注意,为了获得 datetime,我们使用 datetimes() .

关于python - 如何使用假设库创建日期时间索引 pandas DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072179/

相关文章:

python - PyTest - 登录生产代码

python - 循环没有正确执行

python - 从列表列表生成 pandas 数据框

python - 将 2D 列表分配给 2 个 Dataframe 列 Pandas

python - 使用 Seaborn FacetGrid 从数据框中绘制错误条

python - 如何让 pytest 在已安装的模块中发现并运行 doctests?

python - 如何在 vscode 中使用 pytest 测试文件夹内的文件?

python - 需要洞察力 : Using python I am using a regular expression to capture sample restaurant sales data to categorize and convert it to JSON from a . pdf

python - 如何从 Google Compute Engine 访问外部 SFTP

python - 如何在 PDF 的底部(页脚)添加多行?