3

假设我创建了一个简单的 DataFrame,如下所示:

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

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

4

1 回答 1

2

您的构造不保留数据类型;如果您以这种方式构建,您将首先保留它们。

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
于 2013-06-29T13:44:34.323 回答