pandas 如何在dataframe中创建基于年和月名称的日期?

0lvr5msh  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(171)

我想创建一个基于年份和月份名称的日期。我写了一个代码来在控制台中打印日期。
密码:

import pandas as pd
import numpy as np

data = {'month': ['APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER', 'JANUARY', 'FEBRUARY', 'MARCH'],
    'kpi': ['SALES', 'SALES QUANTITY', 'SALES', 'SALES', 'SALES', 'SALES', 'SALES', 'SALES QUANTITY', 'SALES', 'SALES', 'SALES', 'SALES'],
    'financial_year': [2022, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023]
    }

# Create DataFrame

df = pd.DataFrame(data)
print (pd.to_datetime(df['financial_year'].astype(str)  + df['month'], format='%Y%B'))

它生成如下输出:

0    2022-04-01
1    2023-05-01
2    2023-06-01
3    2023-07-01
4    2023-08-01
5    2023-09-01
6    2023-10-01
7    2023-11-01
8    2023-12-01
9    2023-01-01
10   2023-02-01
11   2023-03-01

但我想生成以下格式的输出:

0    2022-04-30
1    2023-05-01
2    2023-06-30
3    2023-07-31
4    2023-08-31
5    2023-09-30
6    2023-10-31
7    2023-11-01
8    2023-12-31
9    2023-01-31
10   2023-02-28 
11   2023-03-31

所需的输出取决于某些条件:
1.如果kpisales,则date中的day应该是该特定月份的最后一天,否则应该是01
1.对于月份的最后一天应以闰年的四月为基准。
当所有列都是对象类型时,我需要输出。
有谁能提出一个解决方案吗?

7dl7o3gd

7dl7o3gd1#

使用kpi筛选SALES的行,并将offsets.MonthEnd添加到该月的最后一天:

df['Date'] = pd.to_datetime(df['financial_year'].astype(str)  + df['month'], format='%Y%B')

df.loc[df['kpi'].eq('SALES'), 'Date'] += pd.offsets.MonthEnd(0) 
print (df)
        month             kpi  financial_year       Date
0       APRIL           SALES            2022 2022-04-30
1         MAY  SALES QUANTITY            2023 2023-05-01
2        JUNE           SALES            2023 2023-06-30
3        JULY           SALES            2023 2023-07-31
4      AUGUST           SALES            2023 2023-08-31
5   SEPTEMBER           SALES            2023 2023-09-30
6     OCTOBER           SALES            2023 2023-10-31
7    NOVEMBER  SALES QUANTITY            2023 2023-11-01
8    DECEMBER           SALES            2023 2023-12-31
9     JANUARY           SALES            2023 2023-01-31
10   FEBRUARY           SALES            2023 2023-02-28
11      MARCH           SALES            2023 2023-03-31

相关问题