<p>这就是我可能重新编写代码的方法。我只是简单地将最初的7列简化为一个字典,然后使用<code>pd.DataFrame()</code>将它们转换为一个适当的数据帧。然后,我只需在遍历构造的数据帧时应用<code>if...elif</code>语句。在</p>
<pre><code>import numpy as np
import pandas as pd
Battery_W = 1000
Battery_Wh = 1000/ 3
starting_SOC = 0.75
charge_delay = 5
charging = True
#initialize test Dictionary
test = {}
#add your test elements as a tuple
data = (50.00,50.00,49.99,49.98,49.87,49.76,49.65,49.25,50.00,50.00,50.00,50.00,50.00,50.00,49.99,49.78,49.67,49.46,49.25,49.25,50.00,50.00,50.00,49.95,49.65,49.45,49.65,49.55,50.00,50.00,50.00,50.00,50.00,50.00,50.00,49.95,49.65,49.45,49.65,49.55,49.99,49.68,50.00,50.00,50.00,50.00,50.00,50.00,50.00,50.00)
index = 0
#"Battery Operation mode" is not calculated seperately now
#"Calculate power output required" is not calculated seperately now
for d in data:
if d <= 49.75:
test[index] = {'Freq': d,
'Case': 'C',
'Battery_OP':'Discharging',
'Power_Required':0,
'Battery_Energy':0.0,
'SOC':0,
'Charge_Power' :0.0
}
elif d > 49.75:
test[index] = {'Freq': d,
'Case': 'B',
'Battery_OP': 'Idle',
'Power_Required': 1000,
'Battery_Energy': 0.0,
'SOC': 0,
'Charge_Power': 0.0}
index +=1
#This is how I convert the dictionary into a df for the first-time
year_test = pd.DataFrame(test.values())
year_test['Response_timer'] = year_test.groupby('Battery_OP').cumcount()
year_test['Response_timer'][year_test['Battery_OP'] == 'Idle'] = 0
year_test['ChargePower'] = 0.00
year_test['BatteryEnergy'] = 0.0
year_test['BatteryEnergy'].iloc[0:charge_delay] = Battery_Wh * starting_SOC
j = charge_delay
#instead of using the range(), try to manipulate it using `itertuples()`
#This is most probably where you are losing your time..
for row in year_test.itertuples():
if row.Index <5:
continue
if year_test.iloc[j-charge_delay, 3] > 0 and year_test.iloc[j - ((charge_delay) -1), 3] == 0 :
"charge at max rate"
year_test.iloc[j,7] = Battery_W
year_test.iloc[j,2] = "Charging"
charging = True
elif charging == True and year_test.iloc[j-1,4] < starting_SOC * Battery_Wh:
"check if battery charged"
year_test.iloc[j,7] = Battery_W
year_test.iloc[j,2] = "Charging"
elif year_test.iloc[j-1,4] >= starting_SOC * Battery_Wh or charging == False:
charging = False
year_test.iloc[j,7] = 0.0
"New Battery Energy"
year_test.iloc[j,4] = year_test.iloc[(j-1),4] - ((year_test.iloc[j,3])/60/60) + ((year_test.iloc[j,7])/60/60)
if year_test.iloc[j,4] > Battery_Wh :
year_test.iloc[j,4] = Battery_Wh
"Calculate battery SOC% for empty"
year_test['SOC'] = year_test['BatteryEnergy'] / Battery_Wh * 100
</code></pre>