Pandas 0.15.2 MultiIndex vs. 0.14.1(datetime.date vs. pandas.tslib.Timestamp)

时间:2015-03-09 06:07:19

标签: python pandas

当从Pandas 0.14.1升级到0.15.2时,我经历了我的代码中断,我已将其追溯到现在返回pandas.tslib.Timestamp的MultiIndex赋值,而之前这是一个datetime.date。

有没有其他人经历过类似的事情?这是一个理想的功能,还是0.15.2中的错误?任何建议的修复?

i = [dt.date(2015,1,1), dt.date(2015,1,2), dt.date(2015,1,3)]
idx = pd.MultiIndex.from_product([['a', 'b'], i])

>>> idx
MultiIndex(levels=[[u'a', u'b'], [2015-01-01 00:00:00, 2015-01-02 00:00:00, 2015-01-03 00:00:00]],
           labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

>>> type(idx[0][1])
pandas.tslib.Timestamp

>>> idx.levels[1]
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-11-23, ..., 2015-03-06]
Length: 834, Freq: None, Timezone: None

>>> type(idx.levels[1][0])
Out[29]: pandas.tslib.Timestamp

运行此语句时出现以下错误:

df2.merge(df, left_on=['identifier', 'date'],
                        right_index=True,
                        how='left',
                        suffixes=['', '_dup'])

  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/core/frame.py", line 3919, in merge
    suffixes=suffixes, copy=copy)
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 39, in merge
    return op.get_result()
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 187, in get_result
    join_index, left_indexer, right_indexer = self._get_join_info()
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 264, in _get_join_info
    sort=self.sort)
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 582, in _left_join_on_index
    _get_multiindex_indexer(join_keys, right_ax, sort=sort)
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 542, in _get_multiindex_indexer
    llab, rlab, count = _factorize_keys(level, key, sort=False)
  File "/Users/user4589964/anaconda/envs/madrone_dev/lib/python2.7/site-packages/pandas/tools/merge.py", line 622, in _factorize_keys
    llab = rizer.factorize(lk)
TypeError: Argument 'values' has incorrect type (expected numpy.ndarray, got Index)

1 个答案:

答案 0 :(得分:1)

这是索引构建中的错误,请参阅here

以下是如何使用实际datetime.date对象

的示例
In [8]: pd.MultiIndex.from_arrays([Index([datetime.date(2013,1,1)]),['a']])
Out[8]: 
MultiIndex(levels=[[2013-01-01], [u'a']],
           labels=[[0], [0]])

请记住,datetime.date确实是二等公民,因此会被表示为object dtypes,因此效率不高。您通常应该只使用Timestamps