Python 为什么pd.DataFrame every items的类型是float,而pd.DataFrame的数据类型是object?

Python 为什么pd.DataFrame every items的类型是float,而pd.DataFrame的数据类型是object?,python,pandas,types,series,Python,Pandas,Types,Series,结果表是一个pd.DataFrame 当我 print(type(results_table.loc[0,'Mean recall score'])) 它回来了 <class 'numpy.float64'> 它回来了 object 为什么会有这样的行为?第一个注释df.loc[0,x]只考虑行标签0和列标签x中的值,而不是整个数据帧。现在让我们考虑一个例子: df = pd.DataFrame({'A': [1.5, 'hello', 'test', 2]}, dtype=o

结果表是一个pd.DataFrame

当我

print(type(results_table.loc[0,'Mean recall score']))
它回来了

<class 'numpy.float64'>
它回来了

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
对象
dtype系列只是指向不在连续内存块中的各种对象的指针的集合,数字系列可能就是这样。这与Python
list
相当,并解释了当您使用
object
而不是数字序列时性能不佳的原因


有关上述内容的视觉表示,请参见。

在第一条打印语句中,您将从数据帧中切掉一个元素。您正在查看的单个项目是一个浮动

在第二个print语句中,实际上是拉出一个pandas系列(即拉出整个专栏)并打印该系列的类型


熊猫系列是一个对象,但系列中的每个条目都是一个浮动。因此,这就是您得到结果的原因。

在某些情况下,序列中的每个项目都是浮点,但
dtype
object
。例如,从被强制的文件读取时出现错误;或者,当您使用混合类型(例如浮点和字符串)并在以后用其他浮点替换字符串时;等等。只需直接使用
pd.to_numeric(df['score'])
.astype(float)
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
print(df['A'].map(type))

# 0    <class 'float'>
# 1      <class 'str'>
# 2      <class 'str'>
# 3      <class 'int'>
# Name: A, dtype: object