相关疑难解决方法(0)

DataFrame列中混合的元素类型

考虑以下三个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)

python numpy pandas

9
推荐指数
1
解决办法
2万
查看次数

标签 统计

numpy ×1

pandas ×1

python ×1