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

Dim*_*los 4 python pandas

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

UserId    ProductId    Quantity
1         1            6
1         4            1
1         7            3
2         4            2
3         2            7
3         1            2
Run Code Online (Sandbox Code Playgroud)

现在,我想使用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
Run Code Online (Sandbox Code Playgroud)

并且我想保留第3行和第5行已更改的列表。我该如何实现?

Flo*_*oor 7

使用loc更改数据即

change = df.sample(2).index
df.loc[change,'Quantity'] = 0
Run Code Online (Sandbox Code Playgroud)

输出:

  用户 ID 产品 ID 数量
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]
Run Code Online (Sandbox Code Playgroud)


WeN*_*Ben 6

通过使用 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
Run Code Online (Sandbox Code Playgroud)

  • 太棒了 +1添加“ update_list = dfupdate.index.tolist()”,此操作完成。 (3认同)