python - Pandas 。将值与其他 DataFrame 中的相应范围进行匹配

标签 python pandas dataframe

我有两个数据框。

第一个包含用户 ID 及其分数(分数列)。另一个数据框包含一些阈值和范围名称。

我需要在第一个 df 中创建一个新列,如果点列中的值介于“下限”和“上限”阈值之间,则该新列将是第二个 df 的范围。

enter image description here enter image description here

我尝试使用以下代码:

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/

相关文章:

python - 将带有列名的数据框单独附加到另一个带有数据的数据框

python - 减去数据框的最佳方法

python - 重命名 Pandas 中的多列

python - 生成大量不重复的点列表

python - C相当于Python的struct.pack?

python - 如何删除列表列表中的一个列表的所有元素?

python - 规范化数据框的列

python - DB - 与 MySQL 驱动程序/API OurSQL for Python 的连接?

Python:如何在执行时隐藏索引

printing - 打印效果良好的 matplotlib 的颜色选择