📌  相关文章
📜  获取 Pandas DataFrame 列的数据类型

📅  最后修改于: 2022-05-13 01:55:21.066000             🧑  作者: Mango

获取 Pandas DataFrame 列的数据类型

让我们看看如何获取 Pandas DataFrame 中列的数据类型。要获取数据类型,我们将使用 dtype() 和 type()函数。
示例 1:

python
# importing the module
import pandas as pd
  
# creating a DataFrame   
dictionary = {'Names':['Simon', 'Josh', 'Amen', 'Habby',
                       'Jonathan', 'Nick', 'Jake'],
              'Countries':['AUSTRIA', 'BELGIUM', 'BRAZIL',
                           'JAPAN', 'FRANCE', 'INDIA', 'GERMANY'],
              'Boolean':[True, False, False, True,
                         True, False, True],
              'HouseNo':[231, 453, 723, 924, 784, 561, 403],
              'Location':[12.34, 45.67, 03.45, 17.23,
                          83.12, 90.45, 84.34]}
table = pd.DataFrame(dictionary, columns = ['Names', 'Countries',
                                            'Boolean', 'HouseNo', 'Location'])
  
print("Data Types of The Columns in Data Frame")
display(table.dtypes)
  
print("Data types on accessing a single column of the Data Frame ")
print("Type of Names Column : ", type(table.iloc[:, 0]))
print("Type of HouseNo Column : ", type(table.iloc[:, 3]), "\n")
  
print("Data types of individual elements of a particular columns Data Frame ")
print("Type of Names Column Element : ", type(table.iloc[:, 0][1]))
print("Type of Boolean Column Element : ", type(table.iloc[:, 2][2]))
print("Type of HouseNo Column Element : ", type(table.iloc[:, 3][4]))
print("Type of Location Column Element : ", type(table.iloc[:, 4][0]))


Python3
# importing the module
import pandas as pd
  
# creating a DataFrame   
data = {'Name' : ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age' : [27, 24, 22, 32],
        'Address' : ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification' : ['Msc', 'MA', 'MCA', 'Phd']}
table = pd.DataFrame(data)
  
print("Data Types of The Columns in Data Frame")
display(table.dtypes)


输出

从输出中我们可以观察到,在访问或获取与 DataFrame 分离的单个列时,其类型被转换为 Pandas Series 类型,而与该系列中存在的数据类型无关。在访问熊猫系列的各个元素时,我们得到的数据始终以 numpy.datatype() 的形式存储,无论是 numpy.int64 还是 numpy.float64 或 numpy.bool_ 因此我们观察到 Pandas 数据框自动将数据类型转换为NumPy 类格式。

示例 2:

Python3

# importing the module
import pandas as pd
  
# creating a DataFrame   
data = {'Name' : ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age' : [27, 24, 22, 32],
        'Address' : ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification' : ['Msc', 'MA', 'MCA', 'Phd']}
table = pd.DataFrame(data)
  
print("Data Types of The Columns in Data Frame")
display(table.dtypes)