Python 如果数据类型错误(检查类型),如何跳过加载到数据框的excel文件的行
我刚刚编写了以下代码:Python 如果数据类型错误(检查类型),如何跳过加载到数据框的excel文件的行,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我刚刚编写了以下代码: import os import pandas as pd files = os.listdir(path) #AllData = pd.DataFrame() for f in files: info = pd.read_excel(f, "File") info.fillna(0) try: info['Country'] = info['Country'].astype('str') exc
import os
import pandas as pd
files = os.listdir(path)
#AllData = pd.DataFrame()
for f in files:
info = pd.read_excel(f, "File")
info.fillna(0)
try:
info['Country'] = info['Country'].astype('str')
except ValueError:
continue
try:
info['Name'] = info['Name'].astype('str')
except ValueError:
continue
try:
info['Age'] = info['Age'].astype('int')
except ValueError as error:
continue
writer = pd.ExcelWriter("Output.xlsx")
info.to_excel(writer, "Sheet 1")
writer.save()
它读取一些excel文件,选择一个名为“文件”的工作表,并将其所有数据放入数据框中。
一旦完成,它将返回所有记录
我想要的是检查每一列的所有值的类型,如果该类型不是我想要用于该列的类型,则跳过读取源中的行。
最后,我想在输出中记录适合我想要的类型的数据
我尝试使用astype
,但效果不理想
因此,请阅读source-check-astype-if-not-astype-skip行并继续运行代码。我首先要说的是,类型检查和类型转换是两件不同的事情
Pandas的astype用于类型转换(它将一个类型“转换”为另一个类型,它不会检查某个值是否属于某个类型)
但是,如果您不希望保留不能转换为数字类型的行,可以这样做:
info['Age'] = pd.to_numeric(info['Age'], errors='coerce')
info = info.dropna()
Country object
Name object
Age int64
dtype: object
注意,这里不必使用try-except块。
在这里,我们使用来表示数值
,因为我们可以传递errors='concurve'
,因此如果无法强制转换,则值将为NaN
,然后我们使用dropna()
来删除包含NaN
s的行
有关类型检查的更新:
在这里,我将添加一些您在评论中询问的关于如何检查数据帧中的类型的信息:
- 如何获取熊猫为每列推断的类型
- 如何检查整个数据帧中所有值的类型
- 一些有用的类型检查函数
- Python中检查类型的方法
columns\u dtypes=df.dtypes
它将输出如下内容:
info['Age'] = pd.to_numeric(info['Age'], errors='coerce')
info = info.dropna()
Country object
Name object
Age int64
dtype: object
请注意,您的列“Age”包含一些Nan
值dtype
可以是float64
当一列包含字符串时,dtype
将是object
,当您将excel文件加载到示例中的数据框中时。
有关如何检查对象是否为Python字符串(键入str
)的信息,请参见下文
熊猫文档列出了所有数据类型:
关于数据类型的其他有用信息:
如何检查整个数据帧中所有值的类型?
有很多方法可以做到这一点
这里有一个方法。我选择这段代码是因为它清晰简单:
# Iterate over all the columns
for (column_name, column_data) in info.iteritems():
print("column_name: ", column_name)
print("column_data: ", column_data.values)
# Iterate over all the values of this column
for column_value in column_data.values:
# print the value and its type
print(column_value, type(column_value))
# So here you can check the type and do something with that
# For example, log the error to a log file
一些用于类型检查的有用函数:
object_to_test = 1
print( type(object_to_test) is int)
print( type(object_to_test) in (int, float) ) # Check is is one of those types
print( isinstance(object_to_test, int) )
如何测试对象
(由df.dtypes
返回,与上面的输出类似)是否为字符串?
isinstance(对象到测试,str)
见:
现在,如果您有一列包含字符串(如“hello”、“world”等),其中一些字符串是int
,并且您想检查这些sting是否表示数字或int
,您可以使用以下函数:
如何检查字符串是否为int
def str_is_int(s):
try:
int(s)
return True
except ValueError:
return False
如何检查字符串是否为数字
def str_is_number(s):
try:
float(s)
return True
except ValueError:
return False
Python的字符串有一个方法isdigit()
,但它不能用于检查int或number,因为它将在one=“+1”
或减去one=“-1”
时失败
最后,这里有两种在Python中检查“类型”的常用方法:
object_to_test = 1
print( type(object_to_test) is int)
print( type(object_to_test) in (int, float) ) # Check is is one of those types
print( isinstance(object_to_test, int) )
isinstance(object\u to\u test,str)
将返回True
如果object\u to\u test
类型为str
或str
的任何子类
类型(object\u to\u test)为str
如果object\u to\u test
仅为类型str
(不包括str
的任何子类),则返回True
)
还有一个称为熊猫存根的库,可能对类型安全有用:。此代码无效。不可能将循环分配给这样的变量。我还需要检查类型以记录日志文件,以了解电子表格中的错误在哪里。