results_table 是一个 pd.DataFrame
当我
print(type(results_table.loc[0,'Mean recall score']))
IT回报
<class 'numpy.float64'>
每个项目都是
float
类型但是当我...
print(results_table['Mean recall score'].dtype)
它返回
object
为什么会出现这种行为?
results_table 是一个 pd.DataFrame
当我
print(type(results_table.loc[0,'Mean recall score']))
IT回报
<class 'numpy.float64'>
float
类型print(results_table['Mean recall score'].dtype)
它返回
object
首先需要注意的是,df.loc[0, x]
仅考虑行标签为 0
和列标签为 x
的单元格值,而不是整个数据框。现在让我们来看一个例子:
df = pd.DataFrame({'A': [1.5, 'hello', 'test', 2]}, dtype=object)
print(type(df.loc[0, 'A'])) # type of single element in series
# <class 'float'>
print(df['A'].dtype) # type of series
# object
从下面的代码中可以看出,object
数据类型的序列可以容纳任意的 Python 对象。如果您愿意,甚至可以提取序列中每个元素的类型:
print(df['A'].map(type))
# 0 <class 'float'>
# 1 <class 'str'>
# 2 <class 'str'>
# 3 <class 'int'>
# Name: A, dtype: object
object
dtype系列是指向各种对象的指针集合,这些对象并不像数字系列一样保存在连续的内存块中。这就类似于Python的list
,也解释了为什么使用object
而不是数字系列时性能较差。
有关上述内容的可视化表示,请参见此答案。
dtype
是object
。例如,从强制转换的文件读取时出现错误;或者当您具有混合类型(例如,浮点数和字符串)并在稍后的时间将字符串替换为其他浮点数时等。只需直接使用pd.to_numeric(df['score'])
或.astype(float)
即可。 - rafaelc