2016-08-13 72 views
0

我在蟒含有以下信息的數據幀:如何根據兩個條件添加一列隨機數?

Day   Type  
Weekday  1  
Weekday  2  
Weekday  3  
Weekday  1  
Weekend  2  
Weekend  1 

我想通過生成威布爾隨機數,但在每對「日」和「類型」的添加新的列具有唯一威布爾分佈。

例如,我曾嘗試以下代碼,但他們沒有工作:

df['Duration'][ (df['Day'] == "Weekend") & (df['Type'] == 1) ] = int(random.weibullvariate(5.6/math.gamma(1+1/6),6)) 

df['Duration'] = df['Day','Type'].map(lambda x,y: int(random.weibullvariate(5.6/math.gamma(1+1/10),10)) if x == "Weekday" and y == 1 if x == "Weekend" and y == 1 int(random.weibullvariate(5.6/math.gamma(1+1/6),6))) 

回答

1

定義生成你想要的隨機數的函數,並把它應用到行。

import io 
import random 
import math 
import pandas as pd 

data = io.StringIO('''\ 
Day   Type  
Weekday  1  
Weekday  2  
Weekday  3  
Weekday  1  
Weekend  2  
Weekend  1 
''') 
df = pd.read_csv(data, delim_whitespace=True) 

def duration(row): 
    if row['Day'] == 'Weekend' and row['Type'] == 1: 
     return int(random.weibullvariate(5.6/math.gamma(1+1/6),6)) 
    if row['Day'] == 'Weekday' and row['Type'] == 1: 
     return int(random.weibullvariate(5.6/math.gamma(1+1/10),10)) 

df['Duration'] = df.apply(duration, axis=1) 
相關問題