Python 如何在假设数据帧中实现依赖列
我使用假设数据帧来实现一个数据帧,其中开始时间和结束时间是两列。这是一个春卷:Python 如何在假设数据帧中实现依赖列,python,pandas,python-hypothesis,Python,Pandas,Python Hypothesis,我使用假设数据帧来实现一个数据帧,其中开始时间和结束时间是两列。这是一个春卷: 导入假设。策略为st 导入日志记录 导入日期时间 从假设导入给出 从假说.extra.pandas导入列、数据帧、范围索引 当前时间=datetime.datetime.now().replace(小时=0,分钟=0,秒=0,微秒=0) datetime_st=st.整数( 最小值=(当前时间+datetime.timedelta(小时=4)).timestamp(), 最大值=(当前时间+datetime.time
导入假设。策略为st
导入日志记录
导入日期时间
从假设导入给出
从假说.extra.pandas导入列、数据帧、范围索引
当前时间=datetime.datetime.now().replace(小时=0,分钟=0,秒=0,微秒=0)
datetime_st=st.整数(
最小值=(当前时间+datetime.timedelta(小时=4)).timestamp(),
最大值=(当前时间+datetime.timedelta(小时=20)).timestamp(),
)
df_列={
#省略了其他字段
“开始时间”:{“元素”:datetime,unique:False},
“结束时间”:{“元素”:datetime,unique:False},
}
测试\u dfs=数据\u帧(
索引=范围索引(最小值=20,最大值=100),
columns=[键的列(键,**值),df_columns.items()中的值,
)
@给定值(df=测试值)
def测试(df):
logging.info(df)
断言1
我无法找到一个解决方案来断言每个开始时间至少应比其相应的结束时间大delta。我已经尝试了composite
,但我不确定如何在数据帧的每一行上实现它
在初始化开始时间和结束时间时,有没有一种方法可以强制执行增量作为规则?这里有一种方法可以生成两个时间戳列的数据帧,其中第一个和第二个时间戳列之间的差值至少为3600秒(或其他时间量)。我用的是st.flatmap
import hypothesis.strategies as st
from hypothesis.extra.pandas import column, data_frames, range_indexes, columns
current_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
MIN_DIFF_SECONDS = 3600
two_timestamps_with_diff = st.integers(
min_value = current_time + 3600 * 4,
max_value = current_time + 4600 * 20).flatmap(
lambda n: st.tuples(
st.integers(min_value = n, max_value=n),
st.integers(min_value = n + MIN_DIFF_SECONDS, max_value = n + 3600*10)
))
# sample code to examine the results of this strategy
# for _ in range(10):
# x, y = two_timestamps_with_diff.example()
# print(x, y, y-x)
test_dfs = data_frames(
index=range_indexes(min_size=20, max_size=100),
columns=columns(["start_time", "end_time"], dtype=int),
rows=two_timestamps_with_diff,
)
# sample code to examine the results of this strategy
# res = test_dfs.example()
# res.assign(d = res.end_time - res.start_time)
# a test with an assertion that validates this constraint.
@given(df=test_dfs)
def test_hyothesis(df):
logging.info(df)
assert ((df.end_time - df.start_time) >= MIN_DIFF_SECONDS).all()
# run the test. It passes.
test_hyothesis()
如果要向自动生成的数据帧添加其他列,请执行以下操作(本例中的新列为“a”和“b”):
这在df生成之后起作用。在初始化开始时间和结束时间时,有没有一种方法可以强制执行这个断言。我现在明白你在找什么了。您只想在开始时间+常数<结束时间的地方生成数据?看看这个新答案。如果有帮助,请告诉我。(顺便说一句,这个问题很酷:)谢谢!它确实解决了这个问题。我昨天忙着给相同的逻辑添加额外的列。打开这个线程,我无法实现除了开始时间和结束时间之外,df_列中还有其他字段的情况
from hypothesis.strategies import composite
@composite
def test_df_with_additional_columns(draw, elements=test_dfs):
df = draw(test_dfs)
class GetIndex(st.SearchStrategy[pd.core.indexes.range.RangeIndex]):
def do_draw(self, _):
return df.index
more_col_strategy = data_frames([column('A', dtype=int),
column('B', dtype=float)],
index = GetIndex()
)
more_cols = draw(more_col_strategy)
return pd.concat([df, more_cols], axis=1)
test_df_with_additional_columns().example()