简体   繁体   中英

Python Dataframe: Get number of week days present in last month?

I have df with column day_name . I'm trying to get number of week_days present in last month?

I'm trying to get number of week_days present in last month.

For ex: There are 4 Fridays and 5 Thrusdays in April

df

            day_name            
    0       Friday          
    1       Sunday          
    2       Thursday            
    3       Wednesday          
    4       Monday          

As per python for a single day:

    import calendar
    year = 2020
    month = 4
    day_to_count = calendar.WEDNESDAY
    matrix = calendar.monthcalendar(year,month)
    num_days = sum(1 for x in matrix if x[day_to_count] != 0)

How do i use this in dataframe or any suggestions?

expected output

            day_name     last_months_count      
    0       Friday          4
    1       Sunday          4
    2       Thursday        5    
    3       Wednesday       5   
    4       Monday          4

For last month:

year, month = 2020, 4

start,end = f'{year}/{month}/1', f'{year}/{month+1}/1'

# we exclude the last day
# which is first day of next month
last_month = pd.date_range(start,end,freq='D')[:-1]

df['last_month_count'] = df['day_name'].map(last_month.day_name().value_counts())

Output:

    day_name  last_month_count
0     Friday                 4
1     Sunday                 4
2   Thursday                 5
3  Wednesday                 5
4     Monday                 4

Bonus: to extract last month programatically:

from datetime import datetime
now = datetime.now()

year, month = now.year, now.month

# first month of the year
if month == 1:
    year, month = year-1, 12

Here you go:

from datetime import date, timedelta
from calendar import day_name
import pandas as pd

today = date.today()
dt = date(today.year, today.month, 1) - timedelta(days=1)
day_to_count = {}
month = dt.month
while dt.month == month:
    key = day_name[dt.weekday()]
    day_to_count[key] = day_to_count.get(key, 0) + 1
    dt -= timedelta(days = 1)

df = pd.DataFrame({
    'day_name': ['Friday', 'Sunday', 'Thursday', 'Wednesday', 'Monday']
})

df['last_months_count'] = df['day_name'].apply(lambda day : day_to_count[day])
print(df)

Output:


    day_name  last_months_count
0     Friday                  4
1     Sunday                  4
2   Thursday                  5
3  Wednesday                  5
4     Monday                  4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM