gpt4 book ai didi

python - 如何设置每年一次的 Pandas PeriodIndex?

转载 作者:行者123 更新时间:2023-12-05 04:21:24 25 4
gpt4 key购买 nike

我可以像这样创建季度和月度 PeriodIndex:

idx = pd.PeriodIndex(year=[2000, 2001], quarter=[1,2], freq="Q") # quarterly

idx = pd.PeriodIndex(year=[2000, 2001], month=[1,2], freq="M") # monthly

我希望能够像这样创建一个年度 PeriodIndex:

idx = pd.PeriodIndex(year=[2000, 2001], freq="Y")

相反,这会引发以下错误:

Traceback (most recent call last):
File ".../script.py", line 3, in <module>
idx = pd.PeriodIndex(year=[2000, 2001], freq="Y")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/period.py", line 250, in __new__
data, freq2 = PeriodArray._generate_range(None, None, None, freq, fields)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/arrays/period.py", line 316, in _generate_range
subarr, freq = _range_from_fields(freq=freq, **fields)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/arrays/period.py", line 1160, in _range_from_fields
ordinals.append(libperiod.period_ordinal(y, mth, d, h, mn, s, 0, 0, base))
File "pandas/_libs/tslibs/period.pyx", line 1109, in pandas._libs.tslibs.period.period_ordinal
TypeError: an integer is required

这看起来应该很容易做,但我不明白哪里出了问题。有人可以帮忙吗?

最佳答案

由于当前的实现(至少通过 pandas 1.5.1),

monthyear 都是必需的“字段”。大多数其他字段值将配置为默认值,但是,如果未提供值,则不会定义 monthyear。因此,在这种情况下,月份将保持 None,这会导致显示的错误

TypeError: an integer is required

Here is a link to the relevant section of the source code其中定义了默认值。省略月份字段会导致 [None, None](在本例中)无法转换为 Periodindex。


正确的索引可以按如下方式建立。

idx = pd.PeriodIndex(year=[2000, 2001], month=[1, 1], freq='Y')

导致:

PeriodIndex(['2000', '2001'], dtype='period[A-DEC]')

根据年数,以编程方式生成月份列表也可能有意义:

years = [2000, 2001]
idx = pd.PeriodIndex(year=years, month=[1] * len(years), freq='Y')

作为替代方案,使用 to_datetime 可能更容易+ to_period从 Datetime 索引创建 Period 索引(因为它已经是兼容的形式)

pd.to_datetime([2000, 2001], format='%Y').to_period('Y')

产生相同的 PeriodIndex:

PeriodIndex(['2000', '2001'], dtype='period[A-DEC]')

关于python - 如何设置每年一次的 Pandas PeriodIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74215857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com