python - 为 pandas 中的数据帧中的每一行循环 IF 语句

标签 python pandas numpy

您好,我是来自 SAS 背景的 pandas 新手,我正在尝试使用以下代码将连续变量分段为带。

var_range = df['BILL_AMT1'].max() - df['BILL_AMT1'].min()
a= 10
for i in range(1,a):
    inc = var_range/a
    lower_bound = df['BILL_AMT1'].min() + (i-1)*inc
    print('Lower bound is '+str(lower_bound))
    upper_bound = df['BILL_AMT1'].max() + (i)*inc
    print('Upper bound is '+str(upper_bound))
    if (lower_bound <= df['BILL_AMT1'] < upper_bound):
        df['bill_class'] = i
    i+=1

我希望代码检查 df['BILL_AMT1'] 的值是否在当前循环边界内,并相应地设置 df['bill_class'] .

我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我认为 if 条件计算正确,但错误是由于为新列分配了 for 循环计数器的值。

谁能解释一下出了什么问题或提出替代方案。

最佳答案

为了避免 ValueError ,改变

if (lower_bound <= df['BILL_AMT1'] < upper_bound):
    df['bill_class'] = i

mask = (lower_bound <= df['BILL_AMT1']) & (df['BILL_AMT1'] < upper_bound)
df.loc[mask, 'bill_class'] = i

chained comparison (lower_bound <= df['BILL_AMT1'] < upper_bound)相当于

(lower_bound <= df['BILL_AMT1']) and (df['BILL_AMT1'] < upper_bound)

and运算符导致两个 bool 系列 (lower_bound <= df['BILL_AMT1']) , (df['BILL_AMT1'] < upper_bound)在 bool 上下文中进行评估——即减少为单个 bool 值。 Pandas refuses to reduce系列为单个 bool 值。

相反,要返回 bool 系列,请使用 &运算符而不是 and :

mask = (lower_bound <= df['BILL_AMT1']) & (df['BILL_AMT1'] < upper_bound)

然后将值分配给 bill_class列在哪里mask为 True,请使用 df.loc :

df.loc[mask, 'bill_class'] = i

将数据装箱 df['BILL_AMT1'] ,您可以删除 Python for-loop完全,如 DSM suggests ,使用pd.cut :

df['bill_class'] = pd.cut(df['BILL_AMT1'], bins=10, labels=False)+1

关于python - 为 pandas 中的数据帧中的每一行循环 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40854269/

相关文章:

python - 如何将pandas时间序列图中的xticks更改为每年间隔

python - 使用来自 2 个 numpy 矩阵的数据绘制直方图

python - NamedTuple 声明并在一行中使用

python - 在这个 python 代码中产生 "TypeError character mapping must return integer..."是什么?

python - 将散列分配给 Pandas 中的分类数据行

python - 分组时应用自定义函数返回 NaN

python - 你好,我正在尝试添加周开始列

python - 用 numpy 反转分数矩阵

python - 交替应用于 Pandas

python - 如何找到没有 return 语句的 Python 方法?