Skip to main content
 首页 » 编程设计

python之Pandas irow() 自动将 int 转换为 float

2024年10月24日7arxive

x = DataFrame([(1,2.0),(2,4.0)], columns=['a','b']) 
x.dtypes 
a      int64 
b    float64 
a = x.irow(0) 
a 
output: 
a    1.0 
b    2.0 
Name: 0, dtype: float64 

为什么pandas会自动转为float?在使用 irow 后,如何在不对每个字段使用 astype/cast 的情况下将 int 列保持为 int?

请您参考如下方法:

它返回一个 Series对于那一行,所以 dtype被提升为float由于 float 的存在在 col b

In [33]: 
type(x.irow(0)) 
 
Out[33]: 
pandas.core.series.Series 

该方法也已弃用,您应该使用 iloc :

In [31]: 
x.iloc[0] 
 
Out[31]: 
a    1.0 
b    2.0 
Name: 0, dtype: float64 

实际上这不是一个真正的问题,因为访问一行的特定列将保留 dtype :

In [36]: 
x['a'].iloc[0] 
 
Out[36]: 
1 
 
In [37]: 
type(x['a'].iloc[0]) 
 
Out[37]: 
numpy.int64