Pandas 是一个流行且功能强大的 Python 库,通常用于数据分析和操作。它提供了许多数据结构,包括 Series、DataFrame 和 Panel,用于处理表格和时间序列数据。
Pandas DataFrame 是一种二维表格数据结构。在本文中,我们将介绍确定 Pandas 中列的数据类型的各种方法。在很多情况下,我们都必须在 Pandas DataFrame 中查找列的数据类型。 Pandas DataFrame 中的每一列都可以包含不同的数据类型。
在继续之前,让我们制作一个示例数据框,我们必须在该数据框上获取 Pandas 中列的数据类型
DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)
返回值无
算法
导入 Pandas 库。
使用 pd.DataFrame() 函数创建一个 DataFrame 并将上述数据作为字典传递。
打印DataFrame以检查创建的数据。
使用 info() 方法获取有关 DataFrame 的信息。
打印从info()方法获取的信息。
示例
# import the Pandas library
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({\'Vehicle name\': [\'Supra\', \'Honda\', \'Lamorghini\'],\'price\': [5000000, 600000, 7000000]})
# print the dataframe
print("DataFrame:\n", df)
# use the info() method to get the data type of each column
print(df.info())
输出
DataFrame:
Vehicle name price
0 Supra 5000000
1 Honda 600000
2 Lamorghini 7000000
<class \'pandas.core.frame.DataFrame\'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Vehicle name 3 non-null object
1 price 3 non-null int64
dtypes: int64(1), object(1)
memory usage: 176.0+ bytes
None
方法4:使用describe()函数
describe()方法用于生成DataFrame的描述性统计信息,包括每列的数据类型。
算法
使用 import 语句导入 Pandas 库。
使用 pd.DataFrame() 函数创建 DataFrame 并将给定数据作为字典传递。
打印DataFrame以检查创建的数据。
使用describe()方法获取DataFrame的描述性统计信息。
使用describe()方法的include参数为\'all\'以包含描述性统计中的所有列。
使用 dtypes 属性获取 DataFrame 中每列的数据类型。
打印每列的数据类型。
示例
# import the Pandas library
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({\'Vehicle name\': [\'Supra\', \'Honda\', \'Lamorghini\'],\'price\': [5000000, 600000, 7000000]})
# print the dataframe
print("DataFrame:\n", df)
# use the describe() method to get the descriptive statistics of the dataframe
desc_stats = df.describe(include=\'all\')
# get the data type of each column
dtypes = desc_stats.dtypes
# print the data type of each column
print("Data type of each column in the descriptive statistics:\n", dtypes)
输出
DataFrame:
Vehicle name price
0 Supra 5000000
1 Honda 600000
2 Lamorghini 7000000
Data type of each column in the descriptive statistics:
Vehicle name object
price float64
dtype: object
结论
知道如何获取每一列的数据类型,我们就可以高效地完成各种数据操作和分析工作。根据所使用的方法或功能,每种方法都有其自身的优点和缺点。您可以根据您想要的表达式的复杂程度以及您个人编写代码的偏好来选择您想要的方法。