我正在嘗試使用假設來生成 Pandas 資料幀,其中某些列值依賴于其他列值。到目前為止,我還無法“鏈接”兩列。
此代碼片段:
from hypothesis import strategies as st
from hypothesis.extra.pandas import data_frames , column, range_indexes
def create_dataframe():
id1 = st.integers().map(lambda x: x)
id2 = st.shared(id1).map(lambda x: x * 2)
df = data_frames(index = range_indexes(min_size=10, max_size=100), columns=[
column(name='id1', elements=id1, unique=True),
column(name='id2', elements=id2),
])
return df
生成一個帶有靜態第二列的資料框:
id1 program_id
0 1.170000e 02 110.0
1 3.600000e 01 110.0
2 2.876100e 04 110.0
3 -1.157600e 04 110.0
4 5.300000e 01 110.0
5 2.782100e 04 110.0
6 1.334500e 04 110.0
7 -3.100000e 01 110.0
uj5u.com熱心網友回復:
我認為您是在rows引數之后,它允許您從其他列計算一些列值。例如,如果我們想要一個full_price和sale_price這里出售的價格已經應用于一些折扣列:
from hypothesis import strategies as st
from hypothesis.extra.pandas import data_frames, range_indexes
def create_dataframe():
full = st.floats(1, 1000) # all items cost $1 to $1,000
discounts = st.sampled_from([0, 0.1, 0.25, 0.5])
rows = st.tuples(full, discounts).map(
lambda xs: dict(price=xs[0], sale_price=xs[0] * (1-xs[1]))
)
return data_frames(
index = range_indexes(min_size=10, max_size=100),
rows = rows
)
price sale_price
0 757.264509 378.632254
1 824.384095 618.288071
2 401.187339 300.890504
3 723.193610 650.874249
4 777.171038 699.453934
5 274.321034 205.740776
那么您的示例代碼出了什么問題?看起來您認為id1和id2策略是在行式基礎上相對于彼此定義的,但它們實際上是獨立的 - 并且該shared()策略在列中的每一行之間共享一個值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/347961.html
上一篇:將一列轉換為行和列
