[英]retrieve only months with at least 28 sample days - pandas dataframe
[英]using python i want to apply ifelse condition for 28 days (February) and 30/31 days (others Months) inside function for pandas dataframe
我有一個 dataframe,需要在 python ZC1C425268E68385D14AB5074C17ZA 內實現 28 天(二月)和 30/31 天(其他月份)的多個 if-else 條件
我正在為該場景使用 if-else 條件邏輯,但在這種情況下,我必須實現若干天的邏輯,但我被困在如何自動檢查哪個月有 30/31/28 天
每個月我都會運行這個腳本,所以它會根據提取的日期自動選擇
Input Dataframe
client_id expo_value value cal_value extracted_date
1 126 30 27.06 08/2022
2 135 60 36.18 08/2022
3 144 120 45 08/2022
4 162 30 54.09 08/2022
5 153 90 63.63 08/2022
6 181 120 72.9 08/2022
Input Dataframe
client_id expo_value value cal_value extracted_date Output_Value
1 126 30 27.06 08/2022 126+26.18 = 152.18
2 135 60 36.18 08/2022 261.29+70.02 = 331.31
3 144 120 45 08/2022 557.4+174.19 = 731.59
4 162 30 54.09 08/2022 156.7+ 52.34 = 209.04
5 153 90 63.63 08/2022 444.19+ 182.9 =627.09
6 181 120 72.9 08/2022 700.64+282.19=982.83
我想在下面的 function 中implement 31 days/30 days/28 days
,我嘗試手動entering the number 31(days)
進行計算,但它應該根據哪個月有多少天automatically should pick
def month_data(data):
if (data['value'] <=30).any():
return data['expo_value'] *30/ 31(days) + data['cal_value'] * 45/ 31(days)
elif (data['value'] <=60).any():
return data['expo_value'] *60/ 31(days) + data['cal_value'] * 90/31(days)
elif (data['value'] <=90).any():
return data['expo_value'] *100/31(days) + data['cal_value'] * 120/ 31(days)
else (data['value'] <=120).any():
return np.nan
讓我看看我是否理解正確。 我試圖重現您的 dataframe 的一小部分(下次發布內容時應該這樣做)。 答案如下:
import pandas as pd
from datetime import datetime
import calendar
# I'll make a subset dataframe based on your example
data = [[30, '02/2022'], [60, '08/2022']]
df = pd.DataFrame(data, columns=['value', 'extracted_date'])
# First, turn the extracted_date column into a correct date format
date_correct_format = [datetime.strptime(i, '%m/%Y') for i in df['extracted_date']]
# Second, calculate the number of days per month
num_days = [calendar.monthrange(i.year, i.month)[1] for i in date_correct_format]
num_days
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.