gpt4 book ai didi

Python:TypeError:dtype=datetime64[ns] 和日期之间的比较无效

转载 作者:行者123 更新时间:2023-12-04 04:29:40 24 4
gpt4 key购买 nike

对于当前的项目,我计划通过运行多个循环按时间范围过滤 JSON 文件,每次循环的范围略有不同。但是,下面的代码会产生错误 TypeError: Invalid comparison between dtype=datetime64[ns] and date线路after_start_date = df["Date"] >= start_date .

我已经尝试在 Python 代码以及相应的 JSON 文件中修改日期的格式。是否有任何智能调整来对齐日期类型/格式?

JSON 文件具有以下格式:

[
{"No":"121","Stock Symbol":"A","Date":"05/11/2017","Text Main":"Sample text"}
]

相应的代码如下所示:
import string
import json

import pandas as pd
import datetime
from dateutil.relativedelta import *


# Loading and reading dataset
file = open("Glassdoor_A.json", "r")
data = json.load(file)
df = pd.json_normalize(data)
df['Date'] = pd.to_datetime(df['Date'])


# Create an empty dictionary
d = dict()

# Filtering by date

start_date = datetime.date.fromisoformat('2017-01-01')
end_date = datetime.date.fromisoformat('2017-01-31')

for i in df.iterrows():
start_date += relativedelta(months=+3)
end_date += relativedelta(months=+3)

print(start_date)
print(end_date)

after_start_date = df["Date"] >= start_date
before_end_date = df["Date"] <= end_date

between_two_dates = after_start_date & before_end_date
filtered_dates = df.loc[between_two_dates]

print(filtered_dates)

最佳答案

您可以使用 pd.to_datetime('2017-01-31')而不是 datetime.date.fromisoformat('2017-01-31') .

我希望这有帮助!

关于Python:TypeError:dtype=datetime64[ns] 和日期之间的比较无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61865793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com