我正在尝试创建一个函数,我将。apply()到一个数据帧:
- 从提供的参数中删除一个工作日到函数
- 检查这个新的一天是否在一个特定的日期集合中(格式化为日期时间索引)
我已经简化了函数的逻辑来解决这个问题,稍后我会添加更多的逻辑。
我的函数:
def test(trade_date):
if (trade_date - BDay(1)).isin(pricing_date):
return True
else:
return False
错误:
AttributeError: 'Timestamp' object has no attribute 'isin'
看起来有一个问题使用。isin与时间戳。但是,当我在数据框架内运行代码进行测试时:
df['Check'] = df['test_date'].isin(pricing_date)
返回预期的输出- isin()对该数据可以正常工作。
TradeDate
2023-01-03 False
2023-01-03 False
2023-01-03 False
2023-01-03 False
2023-01-03 False
...
2023-03-22 True
2023-03-22 True
2023-03-22 True
2023-03-22 True
2023-03-22 True
Name: Check, Length: 14324, dtype: bool
.isin()正在被调用的列的数据类型是:datetime64[ns],但不确定如何将函数中的时间戳转换为该数据类型-我在许多地方读到它们实际上是等效的,只是python与pandas的类型。
Name: test_date, Length: 14324, dtype: datetime64[ns]
任何帮助都是感激的!
尝试将时间戳传入.isin -直接在数据框上运行它所期望的输出。
Pandas数据框架apply
对pd.Series
内的值运行函数,而不是对pd.Series
中的函数。因此,trade_date
将是一个时间戳,它没有isin
方法。你应该这样做:
def test(trade_date):
return (trade_date - BDay(1)) in pricing_date
或者更简单:
df['Check'] = (df['test_date']-BDay(1)).isin(pricing_date)