如何通過設定數字隨機填充資料幀的行?例如:
給定一個包含 10 個元素的 Pandas 資料框:
col1
a
b
c
d
e
f
g
h
i
j
如何在另一列的行中隨機填充1和其余的0。例如,我想填充四行,1其余六行0:
col1 col2
a 1
b 0
c 1
d 1
e 0
f 1
g 0
h 0
i 0
j 0
uj5u.com熱心網友回復:
這應該可以解決問題。對于每一行,將 col2 設定為 0 到 1 之間的隨機整數
df["col2"] = df.apply(lambda x: randint(0,1), axis=1)
如果您需要存在 n 個隨機值并設定其余值,您可以嘗試以下操作:
n = 4
df["col2"] = 0
df_to_update = df.sample(n)
df_to_update = 1
df.update(df_to_update)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369027.html
