python - 在长轴上迭代时 Pandas 数据类型发生变化

标签 python pandas

假设我像这样创建了一个简单的 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
-------------

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

最佳答案

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

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 被分成 block 。

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

关于python - 在长轴上迭代时 Pandas 数据类型发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17359248/

相关文章:

python - 如何运行存储在不同文件中的 python 函数

python - 维吉尼亚密码 Python 给出外文字符而不是英语

Python - 比较两列特征,返回两者不共同的值

python - 将我的字典变成 pandas 数据框

python - 将分层 JSON 文件导入 Pandas 数据框

python - 如何从 python 数据框列中的项目列表中提取项目?

python - Numpy Array Division - 不支持的操作数类型/: 'list' and 'float'

python - 如何将 Pandas 中的日期时间列全部转换为相同的时区

python - 获取字典中某些值中最大值的键

python - 如何根据 Pandas DataFrame 中的条件添加每组具有重复值的新列?