[英]How can I randomly change the values of some rows in a pandas DataFrame?
我有一個像下面這樣的pandas Dataframe:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 2
3 2 7
3 1 2
現在,我想使用df.sample(n)隨機選擇此DataFrame的20%行,並將這些行的Quantity列的值更改為零。 我還想保留更改行的索引。 因此生成的DataFrame將是:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 0
3 2 7
3 1 0
我想在列表中保留第3行和第5行的更改。 我怎樣才能做到這一點?
通過使用update
dfupdate=df.sample(2)
dfupdate.Quantity=0
df.update(dfupdate)
update_list = dfupdate.index.tolist() # from cᴏʟᴅsᴘᴇᴇᴅ :)
df
Out[44]:
UserId ProductId Quantity
0 1.0 1.0 6.0
1 1.0 4.0 0.0
2 1.0 7.0 3.0
3 2.0 4.0 0.0
4 3.0 2.0 7.0
5 3.0 1.0 2.0
使用loc
來改變數據即
change = df.sample(2).index
df.loc[change,'Quantity'] = 0
輸出:
UserId ProductId Quantity 0 1 1 0 1 1 4 1 2 1 7 3 3 2 4 0 4 3 2 7 5 3 1 2
change.tolist() : [3, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.