mf17
mf17

Reputation: 111

Using pandas to_datetime in custom function

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?

Upvotes: 0

Views: 432

Answers (1)

PacketLoss
PacketLoss

Reputation: 5746

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

Upvotes: 2

Related Questions