我有两个数据框。
第一个包含用户 ID 及其分数(分数列)。另一个数据框包含一些阈值和范围名称。
我需要在第一个 df 中创建一个新列,如果点列中的值介于“下限”和“上限”阈值之间,则该新列将是第二个 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: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我想我需要在这里使用一些循环来迭代阈值数据帧。
任何有关如何创建新“范围”列的帮助将不胜感激
最佳答案
使用pandas.cut
并从 upper
列创建 bin,并插入 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)
关于python - Pandas 。将值与其他 DataFrame 中的相应范围进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833007/