【问题标题】:How to count days using datetime64[ns] with pandas?如何使用 datetime64[ns] 和 pandas 计算天数?
【发布时间】:2022-01-09 23:28:44
【问题描述】:

这里是大学学生,我必须为数据分析课程分析数据。 我们必须处理关于山上探险的数据集。我想计算登山者从基点到高点花了多少天(expeditions['basecamp_date']&expeditions['highpoint_date'])。 我找到了一种计算天数的方法,但是如何将这些值放在新列中? (expeditions['days_reach_top'])。我希望能够在之后计算平均值等。 这是我现在的代码:

expeditions['basecamp_date']=pd.to_datetime(expeditions['basecamp_date'])
expeditions['highpoint_date']=pd.to_datetime(expeditions['highpoint_date'])
expeditions['termination_date']=pd.to_datetime(expeditions['termination_date'])

date_format = "%Y-%m-%d/ns"

a = datetime.strptime(str(expeditions['basecamp_date']), date_format)
b = datetime.strptime(str(expeditions['highpoint_date']), date_format)
delta = b - a
print (delta.days)

expeditions['days_reach_top']

我知道它不完整,但它给了我ValueError("unconverted data remains: %s" %ValueError("time data %r does not match format %r" %。如何修复时间格式并用它进行微积分? 对于上下文,这是我的数据集的样子:

感谢您的帮助!

【问题讨论】:

    标签: python pandas dataframe datetime google-colaboratory


    【解决方案1】:

    尝试替换

    a = datetime.strptime(str(expeditions['basecamp_date']), date_format)
    b = datetime.strptime(str(expeditions['highpoint_date']), date_format)
    

    a = expeditions['basecamp_date']
    b = expeditions['highpoint_date']
    

    【讨论】:

    • 它一直告诉我'strptime() 参数 1 必须是 str,而不是 Series'..
    • 我认为您在定义 ab 的行中所做的事情是多余的。我编辑了我的答案,现在试试吧。
    • 非常感谢!不知道为什么我添加了这么多不必要的东西哈哈我是新人,谢谢你的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多