pandas DataFrame多列多条件等级赋值pd.cut报错ValueError解决
报错原因
pd.cut()仅支持1维数组作为输入,你直接传入整个DataFrame、同时传入多组bins和labels参数的用法不符合函数要求,所以会抛出维度错误。
正确实现方案
方案1:逐列处理(适合列数少的场景)
直接对两列分别调用pd.cut()即可,代码如下:
import pandas as pd import numpy as np # 构造示例DataFrame df = pd.DataFrame({ 'A': [78.2, 54.0, 45.0, 20.0], 'B': [98.2, 58.0, 49.0, 10.0] }) # 单独处理A列分箱 df['A_op'] = pd.cut(df['A'], bins=[np.NINF, 40, 70, np.inf], labels=[3, 2, 1]).astype(int) # 单独处理B列分箱 df['B_op'] = pd.cut(df['B'], bins=[np.NINF, 45, 80, np.inf], labels=[3, 2, 1]).astype(int)
末尾加astype(int)是因为pd.cut默认返回分类类型,转为整数更符合你预期的输出格式。
方案2:配置化循环处理(适合后续新增列的场景)
如果后续需要处理更多不同阈值的列,可以把配置抽成字典,循环执行分箱逻辑:
col_config = { 'A': {'bins': [np.NINF, 40, 70, np.inf], 'labels': [3,2,1]}, 'B': {'bins': [np.NINF, 45, 80, np.inf], 'labels': [3,2,1]} } for col, config in col_config.items(): df[f'{col}_op'] = pd.cut(df[col], **config).astype(int)
执行后输出的df和你预期的结果完全一致:
A B A_op B_op 0 78.2 98.2 1 1 1 54.0 58.0 2 2 2 45.0 49.0 2 2 3 20.0 10.0 3 3
内容的提问来源于stack exchange,提问作者Mainland
相关产品推荐
相关产品推荐

