gpt4 book ai didi

python - 如何在Pandas DataFrame中随机更改某些行的值?

转载 作者:行者123 更新时间:2023-12-04 22:41:22 29 4
gpt4 key购买 nike

我有一个如下所示的 Pandas 数据框:

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%,并将这些行的“数量”列的值更改为零。我还想保留已更改行的索引。因此,最终的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

关于python - 如何在Pandas DataFrame中随机更改某些行的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46450260/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com