【问题标题】:applying function to dataframe; timestamp.dt将函数应用于数据框;时间戳.dt
【发布时间】:2018-08-04 16:28:06
【问题描述】:

最终我想计算从df['start'] 中的每个日期到该月最后一天的天数,并用结果填充'count' 列。

作为实现这一目标的第一步,calendar.monthrange 方法接受(年,月)参数并返回(第一个工作日,天数)元组。

在将函数应用于数据框或系列对象方面似乎存在一个普遍错误。我想了解,为什么这不起作用。

import numpy as np
import pandas as pd
import calendar

def last_day(row):
    return calendar.monthrange(row['start'].dt.year, row['start'].dt.month)

此行引发 AttributeError: "Timestamp object has no attribute 'dt'":

df['count'] = df.apply(last_day, axis=1)

这是我的数据框的样子:

       start  count
0 2016-02-15    NaN
1 2016-02-20    NaN
2 2016-04-23    NaN

df.dtypes

start    datetime64[ns]
count           float64
dtype: object

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    删除.dt。这通常在访问某种向量时需要。但是当访问单个元素时,它已经是一个datetime 对象:

    代码:

    def last_day(row):
        return calendar.monthrange(row['start'].year, row['start'].month)
    

    为什么:

    这个apply 调用last_day 并传递一个系列。

    df['count'] = df.apply(last_day, axis=1)
    

    然后在last_day 中选择该系列的单个元素:

    row['start'].year
    

    【讨论】:

      【解决方案2】:

      我会这样做:

      from pandas.tseries.offsets import MonthEnd
      
      ## sample data
      d = pd.DataFrame({'start':['2016-02-15','2016-02-20','2016-04-23']})
      
      ## solution
      d['start'] = pd.to_datetime(d['start'])
      d['end'] = d['start'] + MonthEnd(1)
      d['count'] = (d['start'] - d['end']) / np.timedelta64(-1, 'D')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 2020-03-23
        • 2019-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多