I am new to Python 'for' loops, and I'm trying to compute a formula for each day of the year in a dataframe. The formula I am using is as follows: gdd = (((row_min + row_max) / 2) - 7)
. To further explain, I need to find the maximum and minimum temperature for each day, divide them by two, and then subtract 7 from that quotient.
Here is the data:
import pandas as pd
df = {'Date': ['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-02','2021-01-03','2021-01-03','2021-01-03'],
'Time': ['12:00:00 AM', '1:00:00 AM', '2:00:00 AM','12:00:00 AM', '1:00:00 AM', '2:00:00 AM','12:00:00 AM', '1:00:00 AM', '2:00:00 AM'],
'TEMP': ['3', '1', '12','4', '8', '7','9', '12', '8']}
df = pd.DataFrame(df)
Converting the Date column into a datetime
format:
# Convert to datetime format
df['Date']=pd.to_datetime(df['Date'])
# Add column for day of year
df['dayofyear'] = df['Date'].dt.dayofyear
df
The output shows that a day of the year has been correctly assigned.
Here is the loop that I am trying:
for day in df['dayofyear']:
temp = df['TEMP']
row_min = temp.min()
row_max = temp.max()
gdd = (((row_min + row_max) / 2) - 7)
However, the following error is produced:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [83], in <cell line: 15>()
17 row_min = temp.min()
18 row_max = temp.max()
---> 19 gdd = (((row_min + row_max) / 2) - 7)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
How can I correctly write this loop?