gpt4 book ai didi

python - 我可以指定 pandas 的容器从我的数据框中切割为列吗?

转载 作者:行者123 更新时间:2023-12-04 15:08:52 26 4
gpt4 key购买 nike

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

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

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

如果我将 bins 指定为单个数字,pd.cut 会起作用,但我想将 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

关于python - 我可以指定 pandas 的容器从我的数据框中切割为列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65577940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com