python - 熊猫。将值与来自其他 DataFrame 的相应范围匹配
问题描述
我有两个数据框。
第一个包含用户 ID 和他们的分数(点列)。另一个数据框包含一些阈值和范围名称。
我需要在第一个 df 中创建一个新列,如果 points 列的值介于“下”和“上”阈值之间,它将是第二个 df 的范围。
我尝试使用以下代码:
def r(points):
r = thresholds #thresholds is the df from my second screenshot
if r['lower'] <= points < r['upper']:
r['range']
return r['range']
PointsEarned['range'] = PointsEarned.points.map(r)
但是我收到一个错误
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我想我需要在这里使用一些循环来迭代阈值数据帧。
任何有关如何创建新的“范围”列的帮助将不胜感激
解决方案
使用pandas.cut
和箱是从upper
插入列的第一个值的lower
列创建的:
df = pd.DataFrame(data={'upper': [25,50,75,100,150,250],
'lower': [1,25, 50,75,100,150]})
PointsEarned = pd.DataFrame(data={'points': [32,6,80,113]})
bins = np.insert(df['upper'].values, 0, df['lower'].iat[0])
print (bins)
[ 1 25 50 75 100 150 250]
PointsEarned['range'] = pd.cut(PointsEarned.points, bins=bins, right=False)
print (PointsEarned)
points range
0 32 [25, 50)
1 6 [1, 25)
2 80 [75, 100)
3 113 [100, 150)