英文:
Pandas Timestamp and .isin functionality
问题
def test(trade_date):
if (trade_date - BDay(1)).date() in pricing_date.date:
return True
else:
return False
英文:
I am trying to create a function that I will .apply() to a dataframe to:
- Remove one business day from the provided argument into the function
- Check to see if this new day is in a specific collection of dates (formatted as a datetime index)
I have simplified the logic of my function to iron out this issue - I will add more logic later.
My function:
def test(trade_date):
if (trade_date - BDay(1)).isin(pricing_date):
return True
else:
return False
Error:
AttributeError: 'Timestamp' object has no attribute 'isin'
Looks like there is an issue with using .isin with a Timestamp. However, when I run code to test within the dataframe itself:
df['Check'] = df['test_date'].isin(pricing_date)
The expected output is returned - isin() does work properly with this data.
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
The column that .isin() is being called on is of datatype: datetime64[ns], but unsure how to convert the timestamp in my function to this data type - I have read in many places that they are virtually equivalent, just types from python vs pandas.
Name: test_date, Length: 14324, dtype: datetime64[ns]
Any help is appreciated!
Tried passing in a timestamp into .isin - expected output from running it directly on the dataframe.
答案1
得分: 1
pandas的DataFrame 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)
英文:
Pandas dataframe apply
runs the function on all the values inside the pd.Series
rather than the function in the pd.Series
. Thus, trade_date
would be a timestamp, that doesn't have the isin
method. What you should do is something like this:
def test(trade_date):
return (trade_date - BDay(1)) in pricing_date
Or, much simpler:
df['Check'] = (df['test_date']-BDay(1)).isin(pricing_date)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论