Skip to main content
 首页 » 编程设计

python之Pandas 多级索引弄乱了类型

2025年01月19日10soundcode

好的,我在 Pandas 0.21 上,我试图理解以下奇怪的功能:

x = pd.Series(index=[[pd.Timestamp("2015-05-14").date()]], data=[20.0]) 
y = pd.Series(index=[pd.Timestamp("2015-05-14").date()], data=[21.0]) 
 
print(type(pd.Timestamp("2015-05-14").date())) 
print(type(x.index.get_level_values(0)[0])) 
print(type(y.index[0])) 

这里我构造了两个系列 x 和 y。两者都只有一个元素。 x 有一个只有一层的 MultiIndex。 y 有一个正常的索引。 我希望所有打印语句的结果都是

<class 'datetime.date'> 

但是,引入 Multiindex 会弄乱类型吗? 我明白了

<class 'pandas._libs.tslib.Timestamp'> 

请您参考如下方法:

由于性能原因存在问题 date-likes 被转换为 DatetimeIndex,参见 here :

Their was an inconsistency in how date-likes (datetime.date,datetime.datetime,Timestamp) were inferred in a MultiIndex level. This led to the creation of an object dtyped Index rather than a DatetimeIndex. datetime.date are second class objects in pandas as they are not efficiently represented.

If you really really want to create this, you can do this:

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]]) 

所以在你的样本中:

mux = pd.MultiIndex.from_arrays([pd.Index([pd.Timestamp("2015-05-14").date()]),['a']]) 
print (mux) 
MultiIndex(levels=[[2015-05-14], ['a']], 
           labels=[[0], [0]]) 
            
x = pd.Series(index=mux, data=[20.0]) 
y = pd.Series(index=[pd.Timestamp("2015-05-14").date()], data=[21.0]) 
 
print(type(pd.Timestamp("2015-05-14").date())) 
<class 'datetime.date'> 
 
print(type(x.index.get_level_values(0)[0])) 
<class 'datetime.date'> 
 
print(type(y.index[0])) 
<class 'datetime.date'>