将会计年度日期切片,合并并映射到日历年度日期到新列 - python

我有以下熊猫数据框:

Shortcut_Dimension_4_Code     Stage_Code
10225003                      2
8225003                       1
8225004                       3
8225005                       4

它是一个更大的数据集的一部分,我需要能够按月和年进行筛选。我需要从Shortcut_Dimension_4_Code列中大于9999999的值的前两位开始提取会计年度,而对于小于或等于9999999的值从第一位开始。需要将该值加到“ 20”才能产生年份,即“ 20” +“ 8” = 2008 | “ 20” +“ 10” = 2010。

该年“ 2008、2010”需要与阶段代码值(1-12)组合,以产生一个月/年,即02/2010。

然后需要将日期02/2010从会计年度日期转换为日历年度日期,即会计年度日期:02/2010 =日历年度日期:08/2009。结果日期需要在新列中显示。产生的df最终看起来像这样:

Shortcut_Dimension_4_Code     Stage_Code     Date
10225003                      2              08/2009
8225003                       1              07/2007
8225004                       3              09/2007
8225005                       4              10/2007

我是熊猫和python的新手,可以使用一些帮助。我从这个开始:

Shortcut_Dimension_4_Code   Stage_Code  CY_Month    Fiscal_Year
    0   10225003                 2           8.0        10
    1   8225003                  1           7.0        82
    2   8225003                  1           7.0        82
    3   8225003                  1           7.0        82
    4   8225003                  1           7.0        82

我使用.map和.str方法来生成此df,但在2008-2009财政年度,我一直无法弄清楚如何获得财政年度的权利。

参考方案

在下面的代码中,我假设Shortcut_Dimension_4_Code是一个整数。如果是字符串,则可以将其转换或切片,如下所示:df['Shortcut_Dimension_4_Code'].str[:-6]。注释中的更多解释以及代码。

只要您不必处理空值,它就应该起作用。

import pandas as pd
import numpy as np
from datetime import date
from dateutil.relativedelta import relativedelta

fiscal_month_offset = 6

input_df = pd.DataFrame(
    [[10225003, 2],
    [8225003, 1],
    [8225004, 3],
    [8225005, 4]],
    columns=['Shortcut_Dimension_4_Code', 'Stage_Code'])

# make a copy of input dataframe to avoid modifying it
df = input_df.copy()

# numpy will help us with numeric operations on large collections
df['fiscal_year'] = 2000 + np.floor_divide(df['Shortcut_Dimension_4_Code'], 1000000)

# loop with `apply` to create `date` objects from available columns
# day is a required field in date, so we'll just use 1
df['fiscal_date'] = df.apply(lambda row: date(row['fiscal_year'], row['Stage_Code'], 1), axis=1)

df['calendar_date'] = df['fiscal_date'] - relativedelta(months=fiscal_month_offset)
# by default python dates will be saved as Object type in pandas. You can verify with `df.info()`
# to use clever things pandas can do with dates we need co convert it
df['calendar_date'] = pd.to_datetime(df['calendar_date'])

# I would just keep date as datetime type so I could access year and month
# but to create same representation as in question, let's format it as string
df['Date'] = df['calendar_date'].dt.strftime('%m/%Y')

# copy important columns into output dataframe
output_df = df[['Shortcut_Dimension_4_Code', 'Stage_Code', 'Date']].copy()
print(output_df)

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…