我有一个月[11, 2, 6, 10]
的列表和一个看起来像这样的数据帧:
PredictionTargetDateEOM business_days
0 2022-06-30 22
1 2022-06-30 22
2 2022-06-30 22
3 2022-06-30 22
4 2022-06-30 22
... ... ...
172422 2022-11-30 21
172423 2022-11-30 21
172424 2022-11-30 21
172425 2022-11-30 21
172426 2022-11-30 21
我需要检查每一行,看看PredictionTargetDateEOM
中的月份是否在列表中,如果是,请将0.5
添加到该行的business_days
列中。输出如下所示:
PredictionTargetDateEOM business_days
0 2022-06-30 22.5
1 2022-06-30 22.5
2 2022-06-30 22.5
3 2022-06-30 22.5
4 2022-06-30 22.5
... ... ...
172422 2022-11-30 21.5
172423 2022-11-30 21.5
172424 2022-11-30 21.5
172425 2022-11-30 21.5
172426 2022-11-30 21.5
当然,对于数据帧中月份不在列表中的行,这些行的工作日数应该保持不变。我试过这三种方法都没有用:
for row in predicted_df['PredictionTargetDateEOM']:
if row.month in months:
predicted_df['business_days'] += 0.5
^这一个只是将business_days
中的所有值相加。我不知道如何在if语句中选择正确的行。我会使用熊猫ix
属性吗?
predicted_df['business_days'] = df.apply(lambda x: x['business_days'] + 0.5 if x['PredictionTargetDateEOM'].month in months else x['business_days'], axis=1)
这个只是给了我一个空白的数据帧。
predicted_df.loc[predicted_df['PredictionTargetDateEOM'].month in months, 'final_business_days'] = #predicted_df['business_days']+0.5
被注释掉的部分是因为我不知道如何正确地使这个逻辑工作,或者它是否是正确的方法。我知道这是如何设置一个新的值,我不知道我是否可以使用这个逻辑来更新现有的值。
只要您的日期是datetime对象,就可以使用.dt.month.isin()
import pandas as pd
df = pd.DataFrame({'PredictionTargetDateEOM': ['2022-06-30', '2022-06-30'],
'business_days': [22, 22]})
df['PredictionTargetDateEOM'] = pd.to_datetime(df['PredictionTargetDateEOM'])
df.loc[df['PredictionTargetDateEOM'].dt.month.isin([11, 2, 6, 10]), 'business_days'] +=.5
print(df)
输出
PredictionTargetDateEOM business_days
0 2022-06-30 22.5
1 2022-06-30 22.5