簡體   English   中英

為什么 pd.DataFrame 每個項目的類型都是浮動的,而 pd.DataFrame 的 dtype 是對象?

[英]Why the type of pd.DataFrame every items is float, but the dtype of pd.DataFrame is object?

results_table 是一個 pd.DataFrame

當我

print(type(results_table.loc[0,'Mean recall score']))

它返回

<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系列只是指向保存在連續內存塊中的各種對象的指針的集合,數字系列可能就是這種情況。 這與 Python list相當,並解釋了當您使用object而不是數字系列時性能不佳的原因。

另請參閱此答案以獲取上述內容的視覺表示。

在第一個打印語句中,您從數據框中切出一個元素。 您正在查看的單個項目是一個浮點數。

在第二個打印語句中,您實際上是拉出一個熊貓系列(即拉出整個列)並打印該系列的類型。

pandas 系列是一個對象,但該系列中的每個條目都是一個浮點數。 所以這就是你得到你所做的結果的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM