Python 表:`margins=True`显示带`Period`列的`NaN`

Python 表:`margins=True`显示带`Period`列的`NaN`,python,pandas,Python,Pandas,以下代码再现了我遇到的问题: 将熊猫作为pd导入 df=pd.DataFrame( { “a”:[1,1,2,2], “b”:[ pd.期间(“2019Q1”), pd.期间(“2019Q2”), pd.期间(“2019Q1”), pd.期间(“2019Q2”), ], “x”:1.0, } ) 数据透视表(index=“a”、columns=“b”、values=“x”、margins=True) 输出: b 2019Q1 2019Q2全部 A. 1 1.0 1.0 1.

以下代码再现了我遇到的问题:

将熊猫作为pd导入
df=pd.DataFrame(
{
“a”:[1,1,2,2],
“b”:[
pd.期间(“2019Q1”),
pd.期间(“2019Q2”),
pd.期间(“2019Q1”),
pd.期间(“2019Q2”),
],
“x”:1.0,
}
)
数据透视表(index=“a”、columns=“b”、values=“x”、margins=True)
输出:

b 2019Q1 2019Q2全部
A.
1   1.0     1.0     1.0
2   1.0     1.0     1.0
全南1.0
为什么
NaN
小计?我原以为:

b 2019Q1 2019Q2全部
A.
1   1.0     1.0     1.0
2   1.0     1.0     1.0
所有1.0 1.0 1.0

这发生在
Period
列中。

如果其他人偶然发现这个问题,它确实是一个bug,相关的GitHub问题是和


基本问题是由
PeriodIndex
get\u indexer
方法引起的。现在,重新编制索引时,不使用实际的
PeriodIndex
,而是使用
PeriodIndex
\u int64index
。相关代码,并总结如下:

if isinstance(target, PeriodIndex):
    target = target.asi8

if tolerance is not None:
    tolerance = self._convert_tolerance(tolerance, target)
return Index.get_indexer(self._int64index, target, method, limit, tolerance)
如果使用另一个
PeriodIndex
重新编制索引,这显然效果很好,因为目标也会转换为
int
,但如果另一个索引不是
PeriodIndex
,则会导致一些不可靠的行为,下面是一个小的行为示例

>>> i = pd.PeriodIndex([pd.Period("2019Q1", "Q-DEC"), pd.Period("2019Q2", "Q-DEC")])
>>> j = pd.Index([pd.Period("2019Q1", "Q-DEC"), 'All'])
>>> s = pd.Series([1, 2], index=i)
>>> s
2019Q1    1
2019Q2    2
Freq: Q-DEC, dtype: int64
>>> s.reindex(j)
2019Q1   NaN
All      NaN
dtype: float64
>>> s.index._int64index
Int64Index([196, 197], dtype='int64')
>>> s.reindex([196])
196    1
dtype: int64

显然,这不是理想的行为,解决方案是在使用另一个
周期索引
重新编制索引时仅使用
\u int64index
,否则使用常规的
周期索引
。我提交了一份PR来修复这个问题,希望很快就会包括在内。

如果其他人偶然发现这个问题,它确实是一个bug,相关的GitHub问题是和


基本问题是由
PeriodIndex
get\u indexer
方法引起的。现在,重新编制索引时,不使用实际的
PeriodIndex
,而是使用
PeriodIndex
\u int64index
。相关代码,并总结如下:

if isinstance(target, PeriodIndex):
    target = target.asi8

if tolerance is not None:
    tolerance = self._convert_tolerance(tolerance, target)
return Index.get_indexer(self._int64index, target, method, limit, tolerance)
如果使用另一个
PeriodIndex
重新编制索引,这显然效果很好,因为目标也会转换为
int
,但如果另一个索引不是
PeriodIndex
,则会导致一些不可靠的行为,下面是一个小的行为示例

>>> i = pd.PeriodIndex([pd.Period("2019Q1", "Q-DEC"), pd.Period("2019Q2", "Q-DEC")])
>>> j = pd.Index([pd.Period("2019Q1", "Q-DEC"), 'All'])
>>> s = pd.Series([1, 2], index=i)
>>> s
2019Q1    1
2019Q2    2
Freq: Q-DEC, dtype: int64
>>> s.reindex(j)
2019Q1   NaN
All      NaN
dtype: float64
>>> s.index._int64index
Int64Index([196, 197], dtype='int64')
>>> s.reindex([196])
196    1
dtype: int64

显然,这不是理想的行为,解决方案是在使用另一个
周期索引
重新编制索引时仅使用
\u int64index
,否则使用常规的
周期索引
。我提交了一份PR来修复这一问题,希望能很快将其包括在内。

这似乎是一个bug…好的,我会在GitHub上打开一个问题,谢谢。这似乎是一个bug…好的,我会在GitHub上打开一个问题,谢谢