DataFrame列中混合的元素类型

Dro*_*ror 9 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]])
Run Code Online (Sandbox Code Playgroud)

以下是第二列的类型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]
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,所有int的都是铸造的numpy.int64.精细.在第三种情况下,基本上没有铸造.但是,在第二种情况下,整数(3)被转换为numpy.float64; 可能因为其他数字是浮点数.

我怎样才能控制铸件?在第二种情况下,我希望有[float64, int64]或[float, int]作为类型.

解决方法:

使用可调用打印功能可以有一个替代方案来显示在这里.

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

jor*_*ris 12

pandas DataFrame(或系列)的列是同类型的.您可以使用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')
Run Code Online (Sandbox Code Playgroud)

只有泛型'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]
Run Code Online (Sandbox Code Playgroud)

但实际上不建议这样做,因为这会破坏大熊猫的目的(或至少表现).

您是否有理由在同一列中特别想要整数和浮点数?

  • "我被教导如果你可以把某些东西表示为int,那么就不要使用浮点数" - >这一般来说肯定是正确的,但是当你想把这些数据放在同一个地方时,它不再是在numpy(科学蟒蛇)的土地上数组(或本例中的系列)并对其进行性能分析.如果你担心内存,最好调查你是否需要int64/float64,因为int32/float32可能就足够了. (3认同)