當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas dataframe.infer_objects()用法及代碼示例

Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。

Pandas dataframe.infer_objects()函數嘗試推斷輸入對象列的更好的數據類型。此函數嘗試對object-dtyped列進行軟轉換,而使非對象和不可轉換列保持不變。推理規則與常規Series /DataFrame構造過程中的規則相同。

用法: DataFrame.infer_objects()
返回: converted:same type as input object

範例1:采用infer_objects()函數以推斷更好的數據類型。

# importing pandas as pd 
import pandas as pd 
  
# Creating the dataframe  
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100], 
                   "B":[2, 8, 77, 4, 11], 
                   "C":["amy", 11, 4, 6, 9]}) 
  
# Print the dataframe 
df

輸出:

我們來看看 DataFrame 中每一列的dtype(數據類型)。

# to print the basic info 
df.info()

正如我們在輸出中看到的,第一和第三列是object類型。而第二列是int64類型。現在切片該 DataFrame 並從中創建一個新的 DataFrame 。

# slice from the 1st row till end 
df_new = df[1:] 
  
# Let's print the new data frame 
df_new 
  
# Now let's print the data type of the columns 
df_new.info()

輸出:

從輸出中可以看到,列“A”和“C”都是對象類型,即使它們包含整數值。因此,讓我們嘗試infer_objects()函數。

# applying infer_objects() function. 
df_new = df_new.infer_objects() 
  
# Print the dtype after applying the function 
df_new.info()

輸出:

現在,如果我們查看每列的dtype,我們可以看到列“A”和“C”現在是int64類型。

範例2:采用infer_objects()函數為對象推斷更好的數據類型。

# importing pandas as pd 
import pandas as pd 
  
# Creating the dataframe  
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100],  
                   "B":[2 + 2j, 8, 77, 4, 11], 
                   "C":["amy", 11, 4, 6, 9]}) 
  
# Print the dataframe 
df


我們來看看 DataFrame 中每一列的dtype(數據類型)。

# to print the basic info 
df.info()

正如我們在輸出中看到的,第一和第三列是object類型。而第二列是complex128類型。現在切片該 DataFrame 並從中創建一個新的 DataFrame 。

# slice from the 1st row till end 
df_new = df[1:] 
  
# Let's print the new data frame 
df_new 
  
# Now let's print the data type of the columns 
df_new.info()


從輸出中可以看到,列“A”和“C”都是對象類型,即使它們包含整數值。列“B”的情況與此類似。因此,讓我們嘗試infer_objects()函數。

# applying infer_objects() function. 
df_new = df_new.infer_objects() 
  
# Print the dtype after applying the function 
df_new.info()

輸出:

注意,列“B”的dtype不變。infer_objects()函數嘗試進行軟轉換,使非對象和不可轉換列保持不變。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas dataframe.infer_objects()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。