我有一個程式,它使用類似于此處顯示的選中標記答案的掩碼在資料幀中創建多組亂數,df.
使用組中的條件創建 random.randint?
我的代碼:
for city in state:
mask = df['City'] == city
df.loc[mask, 'Random'] = np.random.randint(1, 200, mask.sum())
較大的資料框需要相當長的時間df。有沒有辦法用groupby加快速度?
uj5u.com熱心網友回復:
你可以試試:
df['Random'] = df.assign(Random=0).groupby(df['City'])['Random'] \
.transform(lambda x: np.random.randint(1, 200, len(x)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400816.html
上一篇:如何從csv檔案中洗掉NaN值?
