根据同一行中的值提取单个值 (pandas)

Extracting a single value based on values in the same row (pandas)

我有一个 pandas DataFrame,我正在尝试编写一个代码来接受与项目类型和容量相关的用户输入,并且如果 return '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]})

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,为容量输入 3,则代码应为 return 189.643564,因为它介于 MinMax对应的Type.

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

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

您可以创建字典 types_dict 来代替 if 语句,它映射类型缩写(user_type:'t1'、't2' 或 't3' )对应的类型。

两个条件都可以写

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

作为基于用户输入值的单个查询。然后传给DataFrame.query到select满足条件的行。最后,select 只有 '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