python - 如果数字在 Pandas 的指定范围内,如何返回值

我想根据数字所在的范围返回一个值(1、2、3、4 或 5)。我想定义一个函数并使用 .apply() 将该函数应用于 DataFrame 中的列。 .

在下面的代码中,amount是 DataFrame 中的一个假设列。但是,我收到错误 SyntaxError: invalid syntax在线elif >= 40 amount < 60: (我相信它会在所有其他行上引发相同的错误)。

amount = pd.Series([20, 25, 65, 80])

def miles(amount):
    if 20 >= amount < 40:
        return 1
    elif >= 40 amount < 60:
        return 2
    elif >= 60 amount < 80:
        return 3
    elif >= 80 amount < 100:
        return 4
    elif >= 100 amount < 120:
        return 5
    else:
        pass

感谢任何帮助。谢谢!

最佳答案

对于这种特殊情况,您要将离散的固定宽度整数范围映射到一个数字。这可以使用线性变换来解决。本例中的偏移量为 0。

amount = pd.Series([20, 25, 65, 80])
out = amount.divide(20).astype(int)
out
# returns:
0   1
1   1
2   3
3   4
dtype: int32

对于分箱不是固定宽度的更一般情况,您可以使用 pd.cut

pd.cut(amount, [20, 40, 60, 80, 100, 120], right=False, labels=[1,2,3,4,5]).astype(int)
# returns:
0   1
1   1
2   3
3   4
dtype: int32

https://stackoverflow.com/questions/73279382/

相关文章:

python - 如何按列导出数据框以分隔 csv 文件?以及如何将不同数据框中的列附加到分离的 c

google-cloud-platform - 我无法让 google cloud function

caching - Aerospike 为特定字段设置到期日期

javascript - ECMA脚本 : What does `status` mean in S

c - gcc中的 '-Wextra'和 '-pedantic'有什么区别?

c++ - 子类调用父复制分配而不是移动分配?

delphi - 组件是特定类 - 在 BPL 结构中不起作用

reactjs - 使用 React Router 将可选查询参数添加到动态路径

javascript - 在映射函数中的 .then 内部分配变量

python - 根据另一个的范围和类别填充 Pandas 列