gpt4 book ai didi

python - pandas 在创建面板时保持数据类型

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:54 25 4
gpt4 key购买 nike

如果我创建一个 DataFrame,其中一列是一个对象,另一列是一个整数,将该 DataFrame 放入一个字典中,然后使用该字典创建一个 Panel,整数数据类型消失:

import pandas as pd
import datetime as dt

a=['a' for i in range(1000)]
b=[i for i in range(1000)]
c = {'c':a[:], 'b':b[:]}
df = pd.DataFrame(c)

print df

d = dict()
d['x'] = df
p = pd.Panel(d)

print p['x']

输出:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns (total 2 columns):
b 1000 non-null values
c 1000 non-null values
dtypes: int64(1), object(1)
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns (total 2 columns):
b 1000 non-null values
c 1000 non-null values
dtypes: object(2)

从包含 DataFrame 的字典创建面板时,是否有保留数据类型的方法?

最佳答案

答案是,除非您改变方向,否则无法做到这一点。

解释问题的错误报告在这里: https://github.com/pydata/pandas/issues/359

我引用下面的相关部分:

in the example below, "a" is a mixed type dataframe. Once included in the Panel, all columns become of type object:

[..]

Panel can only be heterogeneous in the items. I just added an orient option to Panel so you can do:

In [4]: panel = Panel.from_dict({'1':a,'2':b}, orient='minor')

In [5]: panel
Out[5]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 30 (major) x 2 (minor)
Items: a to c
Major axis: 0 to 29
Minor axis: 1 to 2

In [6]: panel['a'].values.dtype
Out[6]: dtype('float64')

In [7]: panel['b'].values.dtype
Out[7]: dtype('object')

In [8]: panel['c'].values.dtype
Out[8]: dtype('float64')

关于python - pandas 在创建面板时保持数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17329358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com