我创建了一个描述季节性的自定义函数,并希望通过将该函数应用于熊猫数据框中的一系列日期时间对象来向该数据框中添加新列。我正在尝试创建一个列表,其中包含应用于数据帧中日期的date_season函数的值。
下面的date_season函数中的所有变量的类型均为datetime.date,除了'dif'是datetime.timedelta。
功能如下:
import datetime as dt
import pandas as pd
def date_season(date):
year = date.year
min_season = dt.date(year,1,1)
max_season = dt.date(year,6,30)
dif = abs(max_season - date)
dif_days = dif.days
x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
seasonality = np.sin(x * (np.pi) / 2)
return(seasonality)
这是创建熊猫数据框的方法:
start = dt.date(2017,1,1)
end = dt.date(2019,12,31)
df = pd.DataFrame({'Date': pd.date_range(start, end, freq="D")})
尝试使用季节性参数创建新列表:
z = []
for index, row in df.iterrows():
z.append(date_season(row.Date))
这将返回错误消息:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-105-63e9cb35ed55> in <module>()
1 z = []
2 for index, row in df.iterrows():
----> 3 z.append(date_season(row.Date))
<ipython-input-71-5e2b35e24e38> in date_season(date)
3 min_season = dt.date(year,1,1)
4 max_season = dt.date(year,6,30)
----> 5 dif = abs(max_season - date)
6 dif_days = dif.days
7 x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
pandas\_libs\tslibs\timestamps.pyx in
pandas._libs.tslibs.timestamps._Timestamp.__sub__()
TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'datetime.date'
尝试:
new_df = df.apply(lambda x: date_season(x))
返回
AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index Date')
不确定为什么需要datetime.datetime对象,因为该函数可以使用datetime.date格式的单个输入。有没有更简单的方法可以遍历日期并使用此函数的结果创建新列?
答案 0 :(得分:1)
您需要将min_season和max_season定义为pandas datetime对象,而不是内置的python datetime类。令人困惑,但它们不能完全互换。
def date_season(date):
year = date.year
#use pandas.datetime
min_season = pd.datetime(year,1,1)
max_season = pd.datetime(year,6,30)
dif = abs(max_season - date)
dif_days = dif.days
x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
seasonality = np.sin(x * (np.pi) / 2)
return(seasonality)
现在,您可以对整个数据框使用applymap,也可以对单个列使用apply。
new_df = df.applymap(date_season)
或
df['Date'].apply(date_season)