Pandas基于多列If Else条件生成新列报TypeError如何解决?
报错原因
你报错的核心原因是loc方法的传参格式错误。df.loc[行筛选条件, 列名]只接受最多两个核心位置参数,前者是行筛选的布尔序列,后者是要操作的列名。你把两个判断条件分开作为两个参数传递,第二个参数df['col5']>0被pandas识别为要选择的列名,而Series是不可哈希的类型,自然无法作为列索引查询,触发报错。
正确实现方式
pandas中多个布尔条件判断需要用&(逻辑与)连接,每个判断条件需要用括号包裹,最终把合并后的布尔序列作为loc的行筛选参数,或者直接转成整数赋值更简洁:
import pandas as pd # 方法1:布尔值直接转整数(最简洁,True对应1,False对应0) # 新增col6 df['col6'] = ((df['col4'] > 1) & (df['col5'] > 1)).astype(int) # 新增col7 # 注:当前col7的判断逻辑和col6完全等价,因为col4>1且col5>1时,两者和最小为2+2=4,必然大于2,可自行核对需求是否正确 df['col7'] = ((df['col4'] > 1) & (df['col5'] > 1) & (df['col4'] + df['col5'] > 2)).astype(int) # 方法2:用loc显式赋值(适合需要先默认填充其他值的场景) # 先初始化两列默认值为0 df[['col6', 'col7']] = 0 # 给符合条件的行赋值1 df.loc[(df['col4'] > 1) & (df['col5'] > 1), 'col6'] = 1 df.loc[(df['col4'] > 1) & (df['col5'] > 1) & (df['col4'] + df['col5'] > 2), 'col7'] = 1
运行后最终得到的df结果如下:
| col1 | col2 | col3 | col4 | col5 | col6 | col7 | |
|---|---|---|---|---|---|---|---|
| 0 | 1.36 | 4.31 | 7.66 | 2 | 2 | 1 | 1 |
| 1 | 2.62 | 3.30 | 2.48 | 2 | 1 | 0 | 0 |
| 2 | 5.19 | 3.58 | 1.62 | 0 | 2 | 0 | 0 |
| 3 | 2.06 | 3.16 | 3.50 | 1 | 1 | 0 | 0 |
| 4 | 2.19 | 2.98 | 3.38 | 1 | 1 | 0 | 0 |
内容的提问来源于stack exchange,提问作者user16304089
相关产品推荐
相关产品推荐

