python - 使用假设重复条目的 Pandas 索引示例
问题描述
我想生成一个pandas.Index
重复条目,像这样。
>>> pd.Index(np.random.choice(range(5), 10))
Int64Index([3, 0, 4, 1, 1, 3, 4, 3, 2, 0], dtype='int64')
所以我写了以下策略:
from hypothesis.extra.pandas import indexes
from hypothesis.strategies import sampled_from
st_idx = indexes(
elements=sampled_from(range(5)),
min_size=10,
max_size=10
)
但是,当我尝试借鉴这样的策略时,我收到以下错误:
>>> st_idx.example()
[...]
Unsatisfiable: Unable to satisfy assumptions of condition.
During handling of the above exception, another exception occurred:
[...]
NoExamples: Could not find any valid examples in 100 tries
在一些实验中,我意识到它只有在min_size
小于等于选择数(在这种情况下<= 5)时才有效。然而,这意味着我永远不会得到重复的例子!
我究竟做错了什么?
编辑:显然,默认情况下只有indexes
策略unique
设置为,将其设置为下面答案中提到的也适用于我的方法。True
False
解决方案
如果生成的索引不必具有任何特定的分布,那么获得所需内容的一种方法是使用integers
策略并在需要时使用策略unique
参数indexes
来产生重复:
import hypothesis.strategies as st
st_idx = indexes(
st.integers(min_value=0, max_value=5),
min_size=10, max_size=10,
unique=False
)
st_idx.example()
生产:
Int64Index([4, 1, 3, 4, 2, 5, 0, 5, 0, 0], dtype='int64')
推荐阅读
- python - PyCharm 中的 ModuleNotFoundError
- python - 使任何可访问 Internet 的 python 代码工作(代理 + 自定义 .crt)
- r - 使用 GGPlot 根据 R 中的列值绘制空间数据和颜色
- typescript - 在 IIFE 中创建 Vue 组件方法时如何在 TypeScript 中保留它?
- wikipedia - 维基百科:如何获取所有页面的页面访问次数
- mysql - 如何使用 sqlalchemy to_sql() 和 pandas df 在主键基础上“更新”mysql 中的行?
- javascript - 页面中有几个粘性标题
- python - 具有另一个函数作为可选参数的函数
- artifactory - Artifactory 在通用存储中丢失文件跟踪
- c# - 无法点击 MS Teams ThumbnailCard 的按钮