Python库通常用于处理数据集,可以帮助用户分析,探索和操作数据,被称为Pandas库。当Pandas数据框的任何列不包含单一类型的数据(数字或字符串),但包含混合类型的数据(数字和字符串)时,此类列称为混合数据类型列。
Pandas列中的混合类型是什么?
如你所知,Pandas数据框可以有多个列,因此当某一列没有指定类型的数据时,即,没有特定的数据类型,但包含混合数据,即,数值和字符串值,则该列往往具有混合数据类型。
举个例子:
data_frame = pd.DataFrame( [['tom', 10], ['nick', '15'], ['juli', 14.8]], columns=['Name', 'Age'])
在这里,Age列包含字符串以及数字类型的数据,Age列具有混合数据类型。
混合数据类型的原因
- 缺失值(NaN)
- 不一致性
- 数据输入错误
缺失值(NaN):
表示未定义或不可表示数据的浮点值称为NaN。NaN出现的最常见用例是0/0情况,这会导致混合数据类型并最终导致不正确的结果。
不一致的错误:
由于单元格格式错误,观察到Pandas数据框中的格式不一致。因此,将列的每个单元格转换为正确的格式至关重要。
数据输入错误:
当用户在Pandas数据框中的列中输入数据时出错时,会发生各种情况。它可以是任何错误,在数字类型列中输入字符串数据或在列中留下空值或任何东西。这些错误也可能导致混合数据类型,因此需要修复。
如何识别Pandas列中的混合类型
你可能已经使用了info()函数来检测Pandas数据帧的数据类型,但是在混合数据类型的情况下,使用info()函数是不可能的。为了检测混合数据类型,您需要遍历Pandas数据帧的每一列,并使用api.types.infer_dtypes()函数获取数据类型。
使用语法:
for column in data_frame.columns:
print(pd.api.types.infer_dtype(data_frame[column]))
示例
本例中用于检测混合数据类型的数据帧如下:
# Python program to detect mixed data types in Pandas data frame
# Import the library Pandas
import pandas as pd
# Create the pandas DataFrame
data_frame = pd.DataFrame( [['tom', 10], ['nick', '15'], ['juli', 14.8]], columns=['Name', 'Age'])
# Traverse data frame to detect mixed data types
for column in data_frame.columns:
print(column,':',pd.api.types.infer_dtype(data_frame[column]))
输出
Name : string
Age : mixed-integer
如何处理Pandas列中的混合类型
为了修复Pandas数据框中的混合数据类型,您需要将整个列转换为一种数据类型。这可以使用astype()函数或to_numeric()函数来完成。
使用astype()函数:
Pandas中用于将对象转换为指定数据类型的关键函数称为astype()函数。通过这种方式,我们将看到如何使用astype()函数修复混合数据类型。
本例中用于修复混合数据类型的数据帧如下:
# Python program to fix mixed data types using astype() in Pandas data frame
# Import the library Pandas
import pandas as pd
# Create the pandas DataFrame
data_frame = pd.DataFrame( [['tom', 10], ['nick', '15'], ['juli', 14.8]], columns=['Name', 'Age'])
# Transforming mixed data types to single data type
data_frame[column] = data_frame[column].astype(int)
# Traverse data frame to detect data types after fix
for column in data_frame.columns:
print(column,':',pd.api.types.infer_dtype(data_frame[column]))
输出
Name : string
Age : integer
使用to_numeric()函数:
函数的作用是:将一个参数转换为数值数据类型。通过这种方式,我们将看到如何使用to_numeric()函数修复混合数据类型。
本例中用于修复混合数据类型的数据帧如下:
# Python program to fix mixed data types using to_numeric() in Pandas data frame
# Import the library Pandas
import pandas as pd
# Create the pandas DataFrame
data_frame = pd.DataFrame( [['tom', 10], ['nick', '15'], ['juli', 14.8]], columns=['Name', 'Age'])
# Transforming mixed data types to single data type
data_frame[column] = data_frame[column].apply(lambda x: pd.to_numeric(x, errors = 'ignore'))
# Traverse data frame to detect data types after fix
for column in data_frame.columns:
print(pd.api.types.infer_dtype(data_frame[column]))
输出
Name : string
Age : floating
总结
具有混合类型的Pandas列在分析数据时可能会导致问题,但可以使用本文中的技术找到并解决这些问题。数据科学家和软件开发人员可以通过正确清理和准备数据来保证其分析的准确性和可靠性。