在Python Pandas中获取列的数据类型
让我们看看如何在pandas数据框架中获得列的数据类型。首先,让我们创建一个pandas数据框架。
示例:
# importing pandas library
import pandas as pd
# List of Tuples
employees = [
('Stuti', 28, 'Varanasi', 20000),
('Saumya', 32, 'Delhi', 25000),
('Aaditya', 25, 'Mumbai', 40000),
('Saumya', 32, 'Delhi', 35000),
('Saumya', 32, 'Delhi', 30000),
('Saumya', 32, 'Mumbai', 20000),
('Aaditya', 40, 'Dehradun', 24000),
('Seema', 32, 'Delhi', 70000)
]
# Create a DataFrame
df = pd.DataFrame(employees,
columns = ['Name', 'Age',
'City', 'Salary'])
# show the dataframe
df
输出:
方法1:使用Dataframe.dtypes 属性。
该属性返回一个带有每列数据类型的系列。
语法: DataFrame.dtypes
参数:无。
返回:每一列的dtype。
示例1:获取数据框架所有列的数据类型。
# importing pandas library
import pandas as pd
# List of Tuples
employees = [
('Stuti', 28, 'Varanasi', 20000),
('Saumya', 32, 'Delhi', 25000),
('Aaditya', 25, 'Mumbai', 40000),
('Saumya', 32, 'Delhi', 35000),
('Saumya', 32, 'Delhi', 30000),
('Saumya', 32, 'Mumbai', 20000),
('Aaditya', 40, 'Dehradun', 24000),
('Seema', 32, 'Delhi', 70000)
]
# Create a DataFrame
df = pd.DataFrame(employees,
columns = ['Name', 'Age',
'City', 'Salary'])
# Use Dataframe.dtypes to
# give the series of
# data types as result
datatypes = df.dtypes
# Print the data types
# of each column
datatypes
输出:
数据框架的数据类型
示例2:获取数据框架中单列的数据类型。
#importing pandas library
import pandas as pd
# List of Tuples
employees = [('Stuti', 28, 'Varanasi', 20000),
('Saumya', 32, 'Delhi', 25000),
('Aaditya', 25, 'Mumbai', 40000),
('Saumya', 32, 'Delhi', 35000),
('Saumya', 32, 'Delhi', 30000),
('Saumya', 32, 'Mumbai', 20000),
('Aaditya', 40, 'Dehradun', 24000),
('Seema', 32, 'Delhi', 70000)
]
# Create a DataFrame
df = pd.DataFrame(employees,
columns = ['Name', 'Age',
'City', 'Salary'])
# Use Dataframe.dtypes to give
# data type of 'Salary' as result
datatypes = df.dtypes['Salary']
# Print the data types
# of single column
datatypes
输出:
单一列的数据类型
方法2:使用Dataframe.info()方法。
该方法用于获得数据框架的简明摘要,如。
- 栏目名称
- 列的数据类型
- 数据框架中的行数
- 每一列中的非空条目
- 它还会打印列数、名称和数据类型。
语法: DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)
返回:无,并打印出一个DataFrame的摘要。
示例:获取数据框架所有列的数据类型。
# importing pandas library
import pandas as pd
# List of Tuples
employees = [('Stuti', 28, 'Varanasi', 20000),
('Saumya', 32, 'Delhi', 25000),
('Aaditya', 25, 'Mumbai', 40000),
('Saumya', 32, 'Delhi', 35000),
('Saumya', 32, 'Delhi', 30000),
('Saumya', 32, 'Mumbai', 20000),
('Aaditya', 40, 'Dehradun', 24000),
('Seema', 32, 'Delhi', 70000)
]
# Create a DataFrame
df = pd.DataFrame(employees,
columns = ['Name', 'Age',
'City', 'Salary'])
# Print complete details
# about the data frame
df.info()
输出:
数据框架的摘要,包括数据类型