pandas如何匹配项目类型和容量区间提取同行对应的Days值
解决方案
直接用pandas布尔索引实现,不需要写循环,代码简洁效率更高。你之前实现失败大概率是因为直接拿用户输入的t1/t2/t3代号去匹配DataFrame里的项目类型全称,没有做映射转换导致的。
完整可运行代码
import pandas as pd # 构造示例DataFrame df = pd.DataFrame({ 'Type': ['Wind - Onshore', 'Wind - Onshore', 'Wind - Onshore', 'Wind - Offshore', 'Wind - Offshore','Wind - Offshore', 'Solar PV', 'Solar PV', 'Solar PV'], 'Min': [0.0, 5.0, 10.0, 0.0, 5.0, 10.0, 0.5, 1.0, 2.5], 'Max': [4.9990,9.9990, 19.9990, 4.9990, 9.9990, 19.9990, 0.9990, 2.4999, 4.9990], 'Days': [189.643564, 200.380952, 297.146154, 331.666667, 121.500000, 154.000000, 171.711956, 185.362637, 194.635246] }) # 定义项目类型映射,不要用type作为变量名,会覆盖python内置关键字 type_map = { 't1': 'Wind - Onshore', 't2': 'Wind - Offshore', 't3': 'Solar PV' } # 打印可选类型 print('t1 = Wind - Onshore\nt2 = Wind - Offshore\nt3 = Solar PV\n') # 接收用户输入 input_type = input('Enter Project Type:').strip() input_cap = input('Enter Capacity:').strip() # 简单异常处理,避免输入非法值崩溃 try: # 转换容量为浮点型 cap = float(input_cap) # 转换输入的代号为实际项目类型 real_type = type_map[input_type] except ValueError: print("错误:容量必须为数字") exit() except KeyError: print("错误:项目类型只能输入t1/t2/t3") exit() # 核心筛选逻辑 match_rows = df[(df['Type'] == real_type) & (df['Min'] <= cap) & (df['Max'] >= cap)] if len(match_rows) == 0: print(f"未找到匹配的记录,{input_type}类型无对应容量区间的数据") else: # 取出Days值,如果有多行匹配取第一个即可 days = match_rows['Days'].iloc[0] print(days)
效果验证
输入项目类型t1,容量3,运行后输出结果为189.643564,符合预期要求。
内容的提问来源于stack exchange,提问作者thebearjew24
相关产品推荐
相关产品推荐

