![](/img/trans.png)
[英]Using Python how do I generate a random number within a range for each row in Pandas dataframe?
[英]How can I generate a random number for each row with condition?
我是 Python 的新手,非常感謝您的幫助。
我有一個包含 2000 行和 2 列的數據框:行和百分比。 基本上,我想創建基於以下邏輯的第三列:
希望我設法解釋自己:)
謝謝!
編輯:對於您的問題:
data = {
'Pct': [0.8,0.4,0.3,0.7,0.3,1,0.23,0.75,0.93,0.6],
'Row': [1,2,3,4,5,6,7,8,9,10]
}
df = pd.DataFrame(data, columns = ['Row','Pct'])
df
Row Pct
0 1 0.80
1 2 0.40
2 3 0.30
3 4 0.70
4 5 0.30
5 6 1.00
6 7 0.23
7 8 0.75
8 9 0.93
9 10 0.60
你可以這樣做:
def generate_random_values(row):
pct_value = float(row['Pct'])
# 1 . Generate random no bw 0 and 1
x = np.random.random()
# 2. Init value of new column
new_col = 0
# 3. while x > pct_value, add 1 to new_col and generate new random no
while x > pct_value:
new_col += 1
x = np.random.random()
# 4. Here x < = pct_value, add 1 to new col and return for the current row
new_col += 1
return new_col
接着:
df['new_column'] = df.apply(func=generate_random_values, axis=1)
print (df)
>>>
Row Pct new_column
0 1 0.80 1
1 2 0.40 2
2 3 0.30 1
3 4 0.70 1
4 5 0.30 8
5 6 1.00 1
6 7 0.23 1
7 8 0.75 1
8 9 0.93 1
9 10 0.60 2
在運行上述 function 之前檢查“Pct”列的最小閾值也是一個好主意,因為您不想陷入無限循環......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.