将日期时间中的数据框列值与整数进行比较?

时间:2019-08-09 15:51:44

标签: python dataframe datetime

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

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)

不确定为什么会给我一个错误

3 个答案:

答案 0 :(得分:0)

我假设如果True中的任何年份等于dfA['Date'],您是否希望if子句的计算结果为current? 如果是这样,您可以执行以下操作:

if dfA['Date'].dt.year.eq(current).sum():
   # do something

答案 1 :(得分:0)

# 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')

答案 2 :(得分:0)

出现错误是因为语句dfA['Date'].dt.year == current是pandas.Boolean系列,而不是单个布尔值:

dfA['Date'].dt.year == 2018
# 0     True
# 1    False
# 2    False
# Name: Date, dtype: bool

python if语句不知道该如何处理:if语句下的代码块是否应该运行,因为该系列值中的 any 是真的?还是因为并非所有的值都是正确的,所以不应该运行?还是应该因为Series本身不是伪值(例如None或零)而运行?目的不明确,因此会出错。

如果要对所有符合指定条件的列在DataFrame上执行某些操作,请考虑使用Boolean indexing。您所创建的Series可以用于选择DataFrame的某些行,如下所示:

dfA['example'] = 100
is_matching_year = dfA['Date'].dt.year == 2018
dfA.loc[is_matching_year, 'example'] *= 2
print(dfA[['Date', 'example']])
#         Date  example
# 0 2018-01-02      200
# 1 2016-04-07      100
# 2 2019-09-09      100