Python 在长轴上迭代时,数据类型会发生变化
假设我创建了一个简单的数据帧,如下所示:Python 在长轴上迭代时,数据类型会发生变化,python,pandas,Python,Pandas,假设我创建了一个简单的数据帧,如下所示: 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
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
-------------
有没有办法避免这种情况,使列在迭代时保留其类型?您的构造不会保留数据类型;如果以这种方式构造,首先将保留它们
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()
在不同的轴上使用iloc
,可以看到数据类型被保留
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
不能保证数据类型的保存-请尝试使用多级帧作为报告,以获得更多的控制。我可以问一下原因吗?当简单地迭代条目时,更改底层数据类型似乎有点奇怪,不是吗?您并不是简单地迭代;您正在切片(这是Majorxs的工作)。数据存储在三维数据类型块中;你在分块。啊,我明白了。但是为什么不能保证数据类型呢?在我看来,如果我有一个对象块,所有对象都是x类型,那么它们的任何子集也必须只包含x类型。实际上,您正在执行一种换位类型的操作(例如,在轴1上切片,从轴0和轴2生成一个数据帧)。数据类型是基于列的,所以这会把事情搞混。如果确实要执行此操作,请在生成的帧上尝试
convert\u objects()
,它将清除此问题。
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