我有一个熊猫DataFrame,在这里,我试图写一个代码,接受用户输入的项目类型和容量,并将返回‘天’值,如果输入的容量在Min -最大值范围内,并符合项目类型。
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]})
df用户输入将如下所示:
print('t1 = Wind - Onshore\nt2 = Wind - Offshore\nt3 = Solar PV\n')
t1 = 'Wind - Onshore'
t2 = 'Wind - Offshore'
t3 = 'Solar PV'
type = input('Enter Project Type:')
cap = float(input('Enter Capacity:'))例如,如果用户输入t1表示Project,3输入容量,代码应该返回189.643564,因为它位于对应的Type的Min和Max之间。
我使用for循环/if语句的所有尝试都没有成功。我是新手,如果有人能向我展示一个高效的、可复制的代码来完成这个任务,我将不胜感激。谢谢!
发布于 2021-11-11 23:40:33
与if语句不同,您可以创建一个字典types_dict,它将类型缩写(user_type:'t1‘、't2’或't3')映射到相应的类型。
你可以写这两个条件
df.Type == types_dict[user_type]df.Min <= user_cap <= df.Max作为基于用户输入值的单一查询。然后将其传递给DataFrame.query以选择满足条件的行。最后,只选择'Days‘值。
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]})
print('t1 = Wind - Onshore\nt2 = Wind - Offshore\nt3 = Solar PV\n')
# map type abbreviation to the correct type
types_dict = {
't1': 'Wind - Onshore',
't2': 'Wind - Offshore',
't3': 'Solar PV'
}
user_type = input('Enter Project Type: ')
user_cap = float(input('Enter Capacity: '))
# condition to fulfil.
query = f"Type == '{types_dict[user_type]}' and Min <= {user_cap} <= Max"
# get the 'Days' of the row that satisfy the previous condition
days = df.query(query)['Days'].iat[0]
print("\nDays:", days)输出
t1 = Wind - Onshore
t2 = Wind - Offshore
t3 = Solar PV
Enter Project Type: t1
Enter Capacity: 3
Days: 189.643564发布于 2021-11-11 23:26:53
你应该把float(input('Enter Capacity:'))改成int(...)然后..。
opts = {
't1': 'Wind - Onshore',
't2': 'Wind - Offshore',
't3': 'Solar PV',
}
type = 'Wind - Offshore'
cap = 2
row = df[df['Type'] == opts[type]].iloc[cap]
print(row)输出:
Type Wind - Offshore
Min 10.0
Max 19.999
Days 154.0
Name: 5, dtype: object基本上,它创建一个从tXX到类型的实际显示名称的映射,然后它获取具有该类型的df的所有行,然后从cap索引的选择中获取行。
您可以像这样访问该行中的值:
print(row['Min'], row['Max'], row['Days'])输出:
10.0 19.999 154.0https://stackoverflow.com/questions/69936149
复制相似问题