2013-06-28 90 views
2

时改变比方说,我创建了一个简单的数据帧像这样:熊猫数据类型遍历长轴

import pandas as pd 
import datetime as dt 
import heapq 

a = [1371215933513120, 1371215933513121] 
b = [1,2] 
d = ['h','h'] 
df = pd.DataFrame({'a':a, 'b':b, 'c':[dt.datetime.fromtimestamp(t/1000000.) for t in a], 'd':d}) 
df.index=pd.DatetimeIndex(df['c']) 

d = OrderedDict() 
d['x'] = df 
p = pd.Panel(d) 
p['x']['b'] = p['x']['b'].astype(int) 

counter = 0 
for dt in p.major_axis: 
    print "a", counter, p['x'].dtypes 
    df_s = p.major_xs(dt) 
    print "b", counter, p['x'].dtypes 
    print "-------------" 
    counter += 1 

由三列,其中之一是由指数。如果开始迭代长轴值,则在第一次迭代之后,int列的数据类型将更改为object

a 0 a object 
b  int64 
c object 
d object 
dtype: object 
b 0 a object 
b object 
c object 
d object 
dtype: object 
------------- 
a 1 a object 
b object 
c object 
d object 
dtype: object 
b 1 a object 
b object 
c object 
d object 
dtype: object 
------------- 

有没有办法避免这种情况,以便列在迭代时保留其类型?

+0

D型保鲜不能保证 - 尝试多层次框架为您再版有更多的控制权。 – Jeff

+1

请问为什么?在迭代条目时改变底层dtype似乎有点奇怪,不是吗? –

+0

你不是简单的迭代;你正在切片(这是major_xs)所做的。数据存储在三维dtype块中;你正在切块。 – Jeff

回答

2

您的建筑不保存dtypes;如果你这样构建,你将首先保存它们。

In [18]: df.set_index(['x','b']).to_panel() 
Out[18]: 
<class 'pandas.core.panel.Panel'> 
Dimensions: 3 (items) x 1 (major_axis) x 2 (minor_axis) 
Items axis: a to d 
Major_axis axis: x to x 
Minor_axis axis: 1 to 2 

In [19]: p1 = df.set_index(['x','b']).to_panel() 

这是内部结构; dtypes被分成块。

In [20]: p1._data 
Out[20]: 
BlockManager 
Items: Index([u'a', u'c', u'd'], dtype=object) 
Axis 1: Index([u'x'], dtype=object) 
Axis 2: Int64Index([1, 2], dtype=int64) 
DatetimeBlock: [c], 1 x 1 x 2, dtype datetime64[ns] 
ObjectBlock: [d], 1 x 1 x 2, dtype object 
IntBlock: [a], 1 x 1 x 2, dtype int64 

使用各种轴iloc你可以看到,dtypes被保留

In [21]: p1.iloc[0].dtypes 
Out[21]: 
b 
1 int64 
2 int64 
dtype: object 

In [22]: p1.iloc[:,0].dtypes 
Out[22]: 
a    int64 
c datetime64[ns] 
d   object 
dtype: object 

In [23]: p1.iloc[:,:,0].dtypes 
Out[23]: 
a    int64 
c datetime64[ns] 
d   object 
dtype: object 

In [24]: p1.iloc[:,:,0] 
Out[24]: 
        a       c d 
x             
x 1371215933513120 2013-06-14 09:18:53.513120 h