[英]How to add random values based on values from two rows?
我正在嘗試使用隨機值創建模擬數據。 我為每個組合設置了三個重復項(例如 s1='1' && s2='a')。 對於其中的每一個,我想添加一個隨機的 integer。 我將為 s1 和 s2 的每個組合手動更改 randint() 的范圍,因為我不知道如何以編程方式進行。 建議將不勝感激,但這不是我問題的重點。
import pandas as pd
import numpy as np
import random
s1 = pd.Series(['1', '3', '5', '7', '9'])
df = pd.DataFrame(columns=['s1', 's2', 's3'])
df['s1'] = s1.repeat(9)
s2 = ['a', 'b', 'c']
df['s2'] = np.tile(s2, len(df)//len(s2))
#my attempt
for i in df:
if ['s1']=='3' and ['s2']=='b':
density['s2'] = density['s3'].concat(random.randint(28,32))
我會很感激任何幫助!
您可以使用每個組合的邊界字典和groupby.transform
:
import numpy as np
bounds = {('1', 'a'): (10, 20), ('1', 'b'): (100, 200)}
def rnd(g):
a,b = bounds.get(g.name, (0,2))
return np.random.randint(a, b, size=len(g))
df['s3'] = df.groupby(['s1', 's2'])['s1']. transform(rnd)
例子:
s1 s2 s3
0 1 a 15
0 1 b 127
0 1 c 0
0 1 a 16
0 1 b 170
0 1 c 1
0 1 a 12
0 1 b 174
0 1 c 0
1 3 a 0
1 3 b 0
1 3 c 0
1 3 a 1
1 3 b 1
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.