将熊猫系列日期时间“月”号转换为月文本

时间:2020-08-18 23:27:01

标签: python pandas datetime tuples series

我无法将月份数从熊猫中的日期转换为整数或数字。

我给。我尝试了各种可能的方式将熊猫月份号转换为月份名称,以便于查看。我得到错误。我曾尝试将month_name用于熊猫系列,创建一个包含月份数字和月份名称的字典(出现错误),我可以将系列转换为字符串,但不能转换为int,我创建了一个单独的元组,似乎没有任何作用。

我意识到我需要将系列(可以用来做数学运算)转换为数字。

使用熊猫系列月份的名字给我:

<bound method Pandas Delegate._add_ delegate accessors.<locals>._create_delegator_method.<locals>.f of <pandas.core.indexes.accessors.DatetimeProperties object at 0x000001F8A776D0F0>>

虽然不是错误,但也没有用。

使用元组时,出现以下错误:元组索引必须是整数或切片,而不是Series。我之所以这样,是因为它能很好地工作,而不是尝试将系列转换为整数,而不是尝试通过某种方式将其转换为“ 。”

'''
creating a tuple of month numbers
'''
num_to_month = ('tuple of months in order','January', 'February', 'March', 'Apil', 'May',
                'June', 'July', 'August', 'September', 'October', 'November', 'December')

'''
create list of new forecasts
'''
files_to_process = sorted(glob('*CAH_KEY_STRATEGY_DOC*.xlsx'))
print(files_to_process)

'''
update the files to process to add the fiscal quarter info and save back to same name
'''
for file in files_to_process:
    df = pd.read_excel(file)
    df.fillna(0, inplace=True)
    df['fiscal_yr_qtr'] = pd.PeriodIndex([date - pd.tseries.offsets.DateOffset(days=1) + pd.tseries.offsets.FY5253Quarter(normalize=True, weekday=4,startingMonth=4, qtr_with_extra_week=1, variation='last') for date in df.task_date], freq='Q-APR')
    df['month'] = df.task_date.dt.month
    # y = df['month'].to_int
    # print(y)
    # z= int(y)
    # print(y)
    df['year'] = df.task_date.dt.year
    df['day'] = df.task_date.dt.day
    df['fiscal_qtr'] = pd.PeriodIndex([date - pd.tseries.offsets.DateOffset(days=1) + pd.tseries.offsets.FY5253Quarter(normalize=True, weekday=4,startingMonth=4, qtr_with_extra_week=1, variation='last') for date in df.task_date], freq='Q-APR').quarter
    df.loc[((df.task_date.dt.month >= 5) | ((df.task_date.dt.month == 4) & (df['fiscal_qtr'] == 1))), 'fiscal_yr'] = df.task_date.dt.year + 1
    df.loc[((df.task_date.dt.month <= 4) & (df['fiscal_qtr'] != 1)), 'fiscal_yr'] = df.task_date.dt.year
    df['total_expenses'] = df['costs'] + df['3rd_prty']
    df['total_spend'] = df['fees'] + df['costs'] + df['3rd_prty']
    # df['month_name'] = df.task_date.dt.month_name #added 8/18/2020
    # df['month_name'] = num_to_month[y] # this gives september
    df.to_excel(file, index=False)
    with pd.ExcelWriter('output.xlsx', datetime_format='YYYY-MM-DD HH:MM:SS') as writer:
        df.to_excel(writer, sheet_name='Sheet_name_1')

1 个答案:

答案 0 :(得分:0)

如果您的日期采用日期时间格式: df [“ Date”] = pd.to_datetime(df [“ Date”],format =“%y-%m-%d%H:%M:%S”) 您可以根据需要直接更改格式。名称月份以%B格式化 检查文档: https://stackabuse.com/how-to-format-dates-in-python/ 如果您希望其他列包含此信息,请使用 df [“ Date_2”] = df [“ Date”]。dt.strftime('%d-%b-%Y')