我可以将 pandas 的分箱指定为数据框中的列吗?
Can I specify the bins for pandas cut as columns from my dataframe?
希望这是一个非常简单的方法,但对于解决我的问题的正确 pandas 方法,我有点困惑。
我正在尝试根据我的数据框中 'Value' 列中的数字评估 Band,基于它们是低于、介于还是高于其他两列(Limit1 和 Limit2)中的值.例如:
Value Limit1 Limit2 Band
3 2 5
5 6 7
5 4 8
9 6 7
2 4 5
pd.cut 如果我将 bins 指定为单个数字,则可以工作,但我想将 bins 指定为数据框中的列,以便每一行都有自己特定的 bins,如下所示
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 扩展到五个或六个,而且我不希望有嵌套代码。
非常感谢!
让我们试试 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
希望这是一个非常简单的方法,但对于解决我的问题的正确 pandas 方法,我有点困惑。
我正在尝试根据我的数据框中 'Value' 列中的数字评估 Band,基于它们是低于、介于还是高于其他两列(Limit1 和 Limit2)中的值.例如:
Value Limit1 Limit2 Band
3 2 5
5 6 7
5 4 8
9 6 7
2 4 5
pd.cut 如果我将 bins 指定为单个数字,则可以工作,但我想将 bins 指定为数据框中的列,以便每一行都有自己特定的 bins,如下所示
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 扩展到五个或六个,而且我不希望有嵌套代码。
非常感谢!
让我们试试 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