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)
但实际上不建议这样做,因为这会破坏大熊猫的目的(或至少表现).
您是否有理由在同一列中特别想要整数和浮点数?
| 归档时间: |
|
| 查看次数: |
19608 次 |
| 最近记录: |