Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

python - applying function to dataframe; timestamp.dt

Ultimately I want to calculate the number of days to the last day of the month from every date in df['start'] and populate the 'count' column with the result.

As a first step towards that goal the calendar.monthrange method takes (year, month) arguments and returns a (first weekday, number of days) tuple.

There seems to be a general mistake regarding applying functions to dataframes or series objects. I would like to understand, why this isn't working.

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)

This line raises an AttributeError: "Timestamp object has no attribute 'dt'":

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

this is what my dataframe looks like:

       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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remove the .dt. This is generally needed when accessing a vector of some sort. But when accessing an individual element it will already be a datetime object:

Code:

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

Why:

This apply calls last_day and passes a Series.

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

In last_day you then select a single element of the series:

row['start'].year

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...