基于同一行中的值提取单个值(panda)



我有一个pandas 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]})
df

用户输入如下所示:

print('t1 = Wind - Onshorent2 = Wind - Offshorent3 = Solar PVn')
t1 = 'Wind - Onshore'
t2 = 'Wind - Offshore'
t3 = 'Solar PV'
type = input('Enter Project Type:')
cap = float(input('Enter Capacity:'))

例如,如果用户输入t1作为"项目类型",输入3作为"容量",则代码应返回189.643564,因为它位于相应TypeMinMax之间。

我使用for循环/if语句的所有尝试都没有成功。我是新手,如果有人能向我展示一个高效且可复制的代码来完成这项任务,我将不胜感激。谢谢

您可以创建一个字典types_dict来代替if语句,该字典将类型缩写(user_type:'t1'、't2'或't3'(映射到相应的类型。

你可以写两个条件

  1. df.Type == types_dict[user_type]
  2. df.Min <= user_cap <= df.Max

作为基于用户输入值的单个查询。然后将其传递给DataFrame.query以选择满足条件的行。最后,只选择"天数"值。

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 - Onshorent2 = Wind - Offshorent3 = Solar PVn')
# 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

您应该将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.0

最新更新