Skip to main content
 首页 » 编程设计

python之将函数应用于数据框;时间戳.dt

2025年01月19日10zhengyun_ustc

最终,我想计算从 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 

请您参考如下方法:

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

代码:

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

为什么:

此 apply 调用 last_day 并传递一个 Series。

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

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

row['start'].year