gpt4 book ai didi

python - 从两个 int64 列构造 PeriodIndex

转载 作者:行者123 更新时间:2023-11-28 17:11:18 26 4
gpt4 key购买 nike

pandas.PeriodIndex 上的文档举如下构造示例:

>>> idx = PeriodIndex(year=year_arr, quarter=q_arr)

并指定这两个参数的类型:

year : int, array, or Series, default None

month : int, array, or Series, default None

但是我在尝试使用这种类型的构造时遇到了 TypeError。

import numpy as np
import pandas as pd

# (Year, Month) MultiIndex'd DataFrame
idx = pd.MultiIndex.from_product(([2017, 2016], range(1, 13)))
df = pd.DataFrame(np.random.randn(24, 2), index=idx, columns=['a', 'b'])

print(df.head())
a b
2017 1 0.406534 -0.516329
2 -0.687286 -0.066606
3 1.493217 0.539294
4 2.069313 0.415216
5 -0.212414 -1.375707

# Seems to mimic the construction example from the docs above:
pd.PeriodIndex(year=df.index.get_level_values(0),
month=df.index.get_level_values(1))
# TypeError: expected string or bytes-like object

# Same issue even if I specify inputs as NumPy arrays or lists
pd.PeriodIndex(year=df.index.get_level_values(0).values,
month=df.index.get_level_values(1).values)
pd.PeriodIndex(year=df.index.get_level_values(0).tolist(),
month=df.index.get_level_values(1).tolist())

额外的问题:我可以解压 MultiIndex 的级别吗?目前我有

year, month = list(zip(*df.index.get_values()))

是否有规定的方法从索引的级别获取可迭代对象?

工作于:pandas 0.20.3。

最佳答案

您可以通过显式指定频率字符串并传入列表/元组来使其工作:

In [10]: pd.PeriodIndex(year=df.index.get_level_values(0).tolist(),
...: month=df.index.get_level_values(1).tolist(), freq='M')
...:
Out[10]:
PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06',
'2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12',
'2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
'2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'],
dtype='period[M]', freq='M')

或者使用 zip 解压:

In [11]: pd.PeriodIndex(year,month=zip(*df.index.get_values()), freq='M')
Out[11]:
PeriodIndex(['2017-01', '2017-01', '2017-01', '2017-01', '2017-01', '2017-01',
'2017-01', '2017-01', '2017-01', '2017-01', '2017-01', '2017-01',
'2016-01', '2016-01', '2016-01', '2016-01', '2016-01', '2016-01',
'2016-01', '2016-01', '2016-01', '2016-01', '2016-01', '2016-01'],
dtype='period[M]', freq='M')

不确定为什么它不能使用 Index 或 numpy 数组。可能是一个错误。

关于python - 从两个 int64 列构造 PeriodIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47289706/

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