python - 将日期时间中的数据框列值与整数进行比较?
问题描述
我有一个带有日期的数据框列(已转换为日期时间格式)。现在我需要将列中的年份与一个数字进行比较,例如:
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)
不知道为什么它给我一个错误
解决方案
# 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')
推荐阅读
- css - 当元素位于 ol 或 ul 标签内时,如何为元素样式属性设置不同的值?
- reactjs - Typescript 和 React 使用空类型数组设置初始状态
- java - java的多线程下载
- node.js - 猫鼬中的model.find({})没有给出db.model.find()的输出
- java - 访问控制练习 - java
- javascript - 拖动 CSS 旋转的 div
- android - 根据动态类型获取领域数据
- python - 是否有更快的方法来写入或读取大约 100 万行的 pandas 数据帧
- tinymce - 如何删除tiny mce插件的表默认属性
- oracle - 空游标和异常