Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having issues with applying a custom function to a column of a data frame in Python. When I try to apply the function to the column of interest, I receive the following error: "TypeError: unsupported operand type(s) for &: 'Timestamp' and 'Timestamp'"

This error is misleading to me as both of the data types appear to be similar. Any idea on what is causing the issue?

import pandas as pd

game_df = pd.DataFrame({'date': ["20151030", "20151219", "20191201"]})

game_df['date'] = pd.to_datetime(game_df['date'], format = "%Y%m%d")


def nba_season(dt):
    if dt >= pd.to_datetime(2015-10-27) & dt <= pd.to_datetime(2016-6-19):
        return "15_16"
    else:
        return "other"


print(game_df['date'].apply(nba_season))

Coming from R, I feel like dates in Python are a little trickier to work with. Is there a better way to approach dates in Python?

question from:https://stackoverflow.com/questions/65661167/using-pandas-to-datetime-in-custom-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

The error you are getting specifies exactly what the issue is.

unsupported operand types for &

& is a bitwise operator which Sets each bit to 1 if both bits are 1

You should use and for your use case.

if dt >= pd.to_datetime(2015-10-27) and dt <= pd.to_datetime(2016-6-19):

Have a read up here on Python operators.


You can use the inbuilt datetime module to do your comparison.

from datetime import datetime

def nba_season(dt):
    if dt >= datetime(2015, 10, 27) and dt <= datetime(2016, 6, 19):
        return "15_16"
    else:
        return "other"

Returns:

>>> print(game_df['date'].apply(nba_season))
0    15_16
1    15_16
2    other
Name: date, dtype: object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...