【问题标题】:Can I specify the bins for pandas cut as columns from my dataframe?我可以将 pandas 的 bin 指定为我的数据框中的列吗?
【发布时间】:2021-01-05 11:23:50
【问题描述】:

希望这是一个非常简单的方法,但我对使用正确的 pandas 方法来解决我的问题有点困惑。

我正在尝试根据它们是否低于、介于或高于其他两列(Limit1 和 Limit2)中的值来评估我的数据框中“值”列中的数字的波段。例如:

Value     Limit1     Limit2    Band
3         2          5         
5         6          7
5         4          8
9         6          7
2         4          5

如果我将 bin 指定为单个数字,pd.cut 可以工作,但我想将 bin 指定为数据框中的列,以便每一行都有自己的特定 bin,如下所示

df['Band'] = df.apply(lambda x: pd.cut(x.value, bins=[0, x.Limit1, x.Limit2, np.inf], labels=['Band1','Band2','Band3']))

这失败了,因为我提供了一个系列,其中 cut 函数需要一个数字。谁能建议我如何使用 pd.cut 做到这一点,或者我应该完全使用不同的 pandas 函数吗?

我宁愿避免使用 np.where,因为我可能不得不将 bin 扩展到五个或六个,并且我不想拥有嵌套代码。

非常感谢!

【问题讨论】:

    标签: python pandas lambda cut


    【解决方案1】:

    让我们试试np.select:

    m1 = df['Value'].lt(df['Limit1'])
    m2 = df['Value'].gt(df['Limit2'])
    
    df['Band'] = np.select([m1, m2], ['band1', 'band3'], 'band2')
    

       Value  Limit1  Limit2   Band
    0      3       2       5  band2
    1      5       6       7  band1
    2      5       4       8  band2
    3      9       6       7  band3
    4      2       4       5  band1
    

    【讨论】:

    • 非常感谢 - 这完全解决了这个问题!我不太了解 numpy,所以我将阅读 select 函数 - 但是,我可以问一下 - 如果我想扩展到四个波段,使用 np.select 这样做的方法是否会添加另一个级别嵌套?
    • @piemashandgravy np.select不用嵌套,可以指定任意数量的条件和对应的选项,我建议你看看np.select函数..虽然你可以使用@ 987654326@ 和 axis=1 在这里,如果你有大量的乐队,但我想这会比 np.select
    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 2020-12-31
    • 1970-01-01
    • 2012-07-04
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多