我有一个 pandas 数据框,其中包含诸如
之类的分数分数 |
---|
0.1 |
0.15 |
0.2 |
0.3 |
0.35 |
0.4 |
0.5 |
等等
我想将这些值分为 0.2 组 因此,如果得分在 0.1 或 0.2 之间,则 sore 中这一行的值将为 0.2 如果分数在 0.2 到 0.4 之间,那么分数的值为 0.4
例如,如果最大分数为 1,我将有 5 个分数桶,0.2 0.4 0.6 0.8 1
所需输出:
分数 |
---|
0.2 |
0.2 |
0.2 |
0.4 |
0.4 |
0.4 |
0.6 |
您可以首先定义一个为您进行舍入的函数:
import numpy as np
def custom_round(x, base):
return base * np.ceil(x / base)
然后使用
.apply()
将函数应用到您的列:
df.score.apply(lambda x: custom_round(x, base=.2))
输出:
0 0.2
1 0.2
2 0.2
3 0.4
4 0.4
5 0.4
6 0.6
Name: score, dtype: float64
np.ceil
:
import pandas as pd
import numpy as np
data = {'score': {0: 0.1, 1: 0.15, 2: 0.2, 3: 0.3, 4: 0.35, 5: 0.4, 6: 0.5}}
df = pd.DataFrame(data)
base = 0.2
df['score'] = base * np.ceil(df.score/base)
print(df)
score
0 0.2
1 0.2
2 0.2
3 0.4
4 0.4
5 0.4
6 0.6