首页 > 解决方案 > 将日期时间中的数据框列值与整数进行比较?

问题描述

我有一个带有日期的数据框列(已转换为日期时间格式)。现在我需要将列中的年份与一个数字进行比较,例如:

Date 
01-02-2018
04-07-2016
09-09-2019

我想做这个比较:

if dfA['Date'].dt.year == current:
   ## do something

有两个问题:

代码给了我这个错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

并且数字来自分配给名称 current 的用户输入(我使用以下代码将 current 转换为 int):

current = int(args.User_Input)

不知道为什么它给我一个错误

标签: pythondataframedatetime

解决方案


# Creating the data you specified
times = ['01-02-2018',
        '04-07-2016',
        '09-09-2019']

#converting to a dataframe
dfA = pd.DataFrame(times)

#Renaming the dataframe to the correct name
dfA.rename(columns={0:'Date'},inplace=True)

#formatting
dfA['Date'] = pd.to_datetime(dfA['Date'], format='%m-%d-%Y')

#User input. Must be an int
currentYear = int(input('Enter Year:'))

#Need to specify the index number using .values[n] to specify which year you're testing against
if dfA['Date'].dt.year.values[0] == currentYear:
    print('Do Something')

推荐阅读