简体   繁体   English

在自定义 function 中使用 pandas to_datetime

[英]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.我在将自定义 function 应用于 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'"当我尝试将 function 应用于感兴趣的列时,我收到以下错误: “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.来自 R,我觉得 Python 中的日期有点难以处理。 Is there a better way to approach dates in Python?有没有更好的方法来处理 Python 中的日期?

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 &是位运算符, Sets each bit to 1 if both bits are 1

You should use and for your use case.您应该将and用于您的用例。

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

Have a read up here on Python operators.在此处阅读 Python 运算符。


You can use the inbuilt datetime module to do your comparison.您可以使用内置的datetime模块进行比较。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM