python - DataFrame 列中的混合类型元素

标签 python numpy pandas

考虑以下三个 DataFrame:

df1 = pd.DataFrame([[1,2],[4,3]])
df2 = pd.DataFrame([[1,.2],[4,3]])
df3 = pd.DataFrame([[1,'a'],[4,3]])

下面是 DataFrame 的第二列的类型:

In [56]: map(type,df1[1])
Out[56]: [numpy.int64, numpy.int64]

In [57]: map(type,df2[1])
Out[57]: [numpy.float64, numpy.float64]

In [58]: map(type,df3[1])
Out[58]: [str, int]

在第一种情况下,所有 int 都被转换为 numpy.int64。美好的。第三种情况基本没有类型转换。但是,在第二种情况下,整数 (3) 被转换为 numpy.float64;可能是因为另一个数字是 float 。

如何控制转换?在第二种情况下,我希望将 [float64, int64][float, int] 作为类型。

解决方法:

使用可调用的打印函数可以有一个解决方法,如图所示 here .

def printFloat(x):
    if np.modf(x)[0] == 0:
        return str(int(x))
    else:
        return str(x)
pd.options.display.float_format = printFloat

最佳答案

pandas DataFrame(或 Series)的列是同类类型的。您可以使用 dtype(或 DataFrame.dtypes)检查它:

In [14]: df1[1].dtype
Out[14]: dtype('int64')

In [15]: df2[1].dtype
Out[15]: dtype('float64')

In [16]: df3[1].dtype
Out[16]: dtype('O')

只有通用的'object' dtype 可以容纳任何python 对象,这样也可以包含混合类型:

In [18]: df2 = pd.DataFrame([[1,.2],[4,3]], dtype='object')

In [19]: df2[1].dtype
Out[19]: dtype('O')

In [20]: map(type,df2[1])
Out[20]: [float, int]

但这真的不推荐,因为这违背了 pandas 的目的(或至少是性能)。

您是否特别希望同一列中同时包含整数和 float ?

关于python - DataFrame 列中的混合类型元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362234/

相关文章:

python - 使用 slider 更新均匀分布的网格中的值

Python - 按列保留第一个唯一值

python - 使用 PySide 时如何有效地将数据从 NumPy 数组传输到 QPolygonF?

python - 单击事件清除 QLineEdit

python - 为什么 Python-NMAP 模块中的 .scan 函数显示 'str' 属性错误?

python - 基于多标签掩码对 numpy 数组求和

python - 计算 Pandas DataFrame 中每一行的频率

python - 将多个文件中的数据检索到多个数据帧中

Python DataFrame : Replace values using dictionary, 如果不在字典中则转换 NaN

python lockf 和 flock 行为