我有一個 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 - 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:'))
例如,如果用戶輸入t1Project Type 和3Capacity ,則代碼應該回傳,189.643564因為它介于相應的Min和之間。MaxType
我所有使用 for 回圈/if 陳述句的嘗試都沒有成功。我是新手,如果有人能向我展示一個高效且可重現的代碼來完成這項任務,我將不勝感激。謝謝!
uj5u.com熱心網友回復:
您可以創建一個字典,而不是 if 陳述句types_dict,它將型別縮寫(user_type:'t1'、't2' 或 't3')映射到相應的型別。
你可以寫兩個條件
df.Type == types_dict[user_type]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 - 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
uj5u.com熱心網友回復:
您應該更改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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357400.html
