根据授权值舍入python数据框列的值 [英] Round values of a python dataframe column according to authorized values

查看:85
本文介绍了根据授权值舍入python数据框列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框:

df = pd.DataFrame({'id':[1,2,3,4], 'score':[0.35,3.4,5.5,8]})
df
  id  score
0  1   0.35
1  2    3.4
2  3    5.5
3  4      8

和此列表:

L = list(range(1,7))
L
[1, 2, 3, 4, 5, 6]

我想将df.scores的值四舍五入为L中最接近的值.因此,我想得到:

I would like to round the values of df.scores to the closest value in L. Consequently, I would like to get :

df
  id  score
0  1      1
1  2      3
2  3      6
3  4      6

我尝试了

df['score'].apply(lambda num : min([list(range(1,7)), key = lambda x:abs(x-num)])

但是它没有用(我是一个初学者,很抱歉,如果这种尝试是没有道理的.)

but it didn't work (I'm a very beginner, sorry if this attempt is a nonsens).

我该怎么办?谢谢您的帮助

How could I do ? Thanks for your help

推荐答案

如果大型DataFrame和性能很重要,则Numpy解决方案会更好:

Numpy solution is better if large DataFrame and performance is important:

L = list(range(1,7))
a =  np.array(L)

df['score'] = a[np.argmin(np.abs(df['score'].values - a[:, None]), axis=0)]
print (df)
   id  score
0   1      1
1   2      3
2   3      5
3   4      6

工作方式:

首先将列表转换为数组:

First is converted list to array:

print (a)
[1 2 3 4 5 6]

然后将[:, None]广播到所有组合的2d数组中减去:

Then subtract with broadcasting with [:, None] to 2d array of all combinations:

print (df['score'].values - a[:, None])
[[-0.65  2.4   4.5   7.  ]
 [-1.65  1.4   3.5   6.  ]
 [-2.65  0.4   2.5   5.  ]
 [-3.65 -0.6   1.5   4.  ]
 [-4.65 -1.6   0.5   3.  ]
 [-5.65 -2.6  -0.5   2.  ]]

将值转换为绝对值:

print (np.abs(df['score'].values - a[:, None]))
[[0.65 2.4  4.5  7.  ]
 [1.65 1.4  3.5  6.  ]
 [2.65 0.4  2.5  5.  ]
 [3.65 0.6  1.5  4.  ]
 [4.65 1.6  0.5  3.  ]
 [5.65 2.6  0.5  2.  ]]

获取最小值的位置:

print (np.argmin(np.abs(df['score'].values - a[:, None]), axis=0))
[0 2 4 5]

因此,如果使用索引获取,则a的值:

So if use indexing get values of a:

print (a[np.argmin(np.abs(df['score'].values - a[:, None]), axis=0)])
[1 3 5 6]

这篇关于根据授权值舍入python数据框列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆