我正在学习机器学习并生成了一个 pandas 数据框,其中包含以下列Id Category Cost_price Sold
。数据框的形状为(100000, 4)
。
这里的目标变量是“已售出”列(1=已售出,0=未售出)
。但没有机器学习算法能够获得足够好的精度,因为数据框中的所有列都是非常随机的。为了向数据帧引入模式,我尝试操作“已售出”列中的一些值。
我想要做的是将 6000 的售出值(value)更改为 1,其中 cost_price 小于 800。但我无法做到这一点。
我是机器学习和 Python 新手。请帮助我
提前致谢
最佳答案
用途:
df.loc[np.random.choice(df.index[df['cost_price'] < 800], 6000, replace=False), 'Sold'] = 1
示例:
df = pd.DataFrame({
'Sold':[1,0,0,1,1,0] * 3,
'cost_price':[500,300,6000,900,100,400] * 3,
})
print (df)
Sold cost_price
0 1 500
1 0 300
2 0 6000
3 1 900
4 1 100
5 0 400
6 1 500
7 0 300
8 0 6000
9 1 900
10 1 100
11 0 400
12 1 500
13 0 300
14 0 6000
15 1 900
16 1 100
17 0 400
<小时/>
df.loc[np.random.choice(df.index[df['cost_price'] < 800], 10, replace=False), 'Sold'] = 1
print (df)
Sold cost_price
0 1 500
1 1 300
2 0 6000
3 1 900
4 1 100
5 1 400
6 1 500
7 1 300
8 0 6000
9 1 900
10 1 100
11 1 400
12 1 500
13 1 300
14 0 6000
15 1 900
16 1 100
17 1 400
说明:
首先按条件过滤索引值 boolean indexing
:
print (df.index[df['cost_price'] < 800])
Int64Index([0, 1, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17], dtype='int64')
然后通过 numpy.random.choice
选择随机 N 值:
print (np.random.choice(df.index[df['cost_price'] < 800], 10, replace=False))
[16 1 7 13 17 12 10 6 5 11]
最后通过索引值设置1
DataFrame.loc
.
关于python - 根据数据框中的其他值更改 pandas 数据框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529663/