Python整数变量用in运算符报错及条件判断失效问题求助
问题分析与解决方案
核心问题
'int' object is not iterable 报错原因
你写的r in (4)里,(4)不是元组,Python会将其解析为单个整数4,用in判断时会尝试遍历这个整数,因此触发迭代错误。正确的单元素元组写法必须带逗号:(4,)。替换==后条件失效的原因
代码里把rec['h']赋值给了变量p,但后续所有条件判断用的是未定义的h,导致这些条件永远不成立,所有记录都进入else分支。
修正后的代码
先修正变量名和元组写法,同时优化逻辑(将映射操作移到循环结束后,避免重复计算):
import pandas as pd # 示例DataFrame df = pd.DataFrame({ 'customer_id': [1,2,3,4], 'r': [4,5,3,2], 'f': [3,4,1,2], 'm': [3,2,1,2], 'h': [3,1,1,2], 'y': [3,4,1,2] }) cust = 'customer_id' # 注意原代码里的'unique_key'与DataFrame列名不匹配,这里修正为实际列名 classes = [] for _, rec in df.iterrows(): r = rec['r'] f = rec['f'] y = rec['y'] h = rec['h'] # 修正变量名,将p改为h if (r in (4,)) and (f in (4,)) and (y in (2,3)) and (h in (3,)): classes.append({rec[cust]: 'Champions'}) elif (r in (4,)) and (f in (4,)) and (y in (1,)) and (h in (2,3)): classes.append({rec[cust]: 'Short Tenure - Promising'}) elif (r in (3,4)) and (f in (3,4)) and (y in (3,)) and (h in (1,2,3)): classes.append({rec[cust]: 'Loyal Customers'}) elif (r in (3,4,5)) and (f in (3,4,5)) and (y in (2,)) and (h in (1,2)): classes.append({rec[cust]: 'Potential Loyalist'}) elif (r in (3,4)) and (f in (3,4)) and (y in (1,)) and (h in (1,)): classes.append({rec[cust]: 'Short Tenure - Average'}) elif (r in (2,)) and (f in (1,2,3)) and (y in (1,2,3)): classes.append({rec[cust]: 'Needs Attention'}) elif (r in (4,)) and (f in (1,2)) and (y in (1,2,3)): classes.append({rec[cust]: 'Occasional and New Customers'}) elif (r in (1,)) and (y in (1,2,3)): classes.append({rec[cust]: "Lost"}) else: print("hi") classes.append({0: [rec['r'], rec['f'], rec['m']]}) # 循环结束后统一生成映射 accs = [list(i.keys())[0] for i in classes] segments = [list(i.values())[0] for i in classes] df['segment_label'] = df[cust].map(dict(zip(accs, segments))) print(df)
更高效的写法(推荐)
用pd.DataFrame.apply替代循环,代码更简洁高效:
def get_segment(row): r = row['r'] f = row['f'] y = row['y'] h = row['h'] if (r == 4) and (f == 4) and (y in (2,3)) and (h == 3): return 'Champions' elif (r == 4) and (f == 4) and (y == 1) and (h in (2,3)): return 'Short Tenure - Promising' elif (r in (3,4)) and (f in (3,4)) and (y == 3) and (h in (1,2,3)): return 'Loyal Customers' elif (r in (3,4,5)) and (f in (3,4,5)) and (y == 2) and (h in (1,2)): return 'Potential Loyalist' elif (r in (3,4)) and (f in (3,4)) and (y == 1) and (h == 1): return 'Short Tenure - Average' elif (r == 2) and (f in (1,2,3)) and (y in (1,2,3)): return 'Needs Attention' elif (r == 4) and (f in (1,2)) and (y in (1,2,3)): return 'Occasional and New Customers' elif (r == 1) and (y in (1,2,3)): return "Lost" else: print("hi") return None df['segment_label'] = df.apply(get_segment, axis=1)
验证结果
运行修正后的代码,示例DataFrame会得到如下结果:
| customer_id | r | f | m | h | y | segment_label |
|---|---|---|---|---|---|---|
| 1 | 4 | 3 | 3 | 3 | 3 | Loyal Customers |
| 2 | 5 | 4 | 2 | 1 | 4 | hi None |
| 3 | 3 | 1 | 1 | 1 | 1 | Short Tenure - Average |
| 4 | 2 | 2 | 2 | 2 | 2 | Needs Attention |
内容的提问来源于stack exchange,提问作者The Great
相关产品推荐
相关产品推荐

