[英]using python i want to apply ifelse condition for 28 days (February) and 30/31 days (others Months) inside function for pandas dataframe
Am having a dataframe,need to implement multiple if-else conditions for 28 days (February) and 30/31 days (other Months) inside python function我有一个 dataframe,需要在 python ZC1C425268E68385D14AB5074C17ZA 内实现 28 天(二月)和 30/31 天(其他月份)的多个 if-else 条件
I am using if-else condition logic for the scenario but in that condition, I have to implement a number of days logic but am stuck on how to check automatically which month has 30/31/28 days我正在为该场景使用 if-else 条件逻辑,但在这种情况下,我必须实现若干天的逻辑,但我被困在如何自动检查哪个月有 30/31/28 天
every month I will be running this script so automatically it will pick based on extracted date每个月我都会运行这个脚本,所以它会根据提取的日期自动选择
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
I want to implement 31 days/30 days/28 days
inside the below function & i tried manually entering the number 31(days)
for calculation but it should automatically should pick
based on which month has how many days我想在下面的 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
Let me see if I understood you correctly.让我看看我是否理解正确。 I tried to reproduce a small subset of your dataframe (you should do this next time you post something).
我试图重现您的 dataframe 的一小部分(下次发布内容时应该这样做)。 The answer is as follows:
答案如下:
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.