如何使用Pandas检查CSV文件中列是否存在且数据类型正确
我需要在把csv文件里的数据加载到数据库表之前,先验证一下这些数据。要检查每一列的名称和它们应该是什么类型的数据。在这方面我试过用ASSERT这个方法,但没有成功。下面是我用来检查的代码片段,但它出错了 -
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
assert df.dtypes.to_dict() == {"Name": str, "Age":int} -- here it gives Assertion error even though the column format is as expected
错误信息
*---------------------------------------------------------------------------
AssertionError 回溯(最近的调用在最下面) Cell In[28], line 1 ----> 1 assert df.dtypes.to_dict() == {"Name": str, "Age":int}
AssertionError: *
2 个回答
0
问题在于你在比较不同的数据类型。
# df.dtypes
Name object
Age int64
dtype: object
所以正确的比较方式应该是:
df.dtypes.astype(str).to_dict() == {'Name': 'object', 'Age': 'int64'}
# True
或者:
import numpy as np
df.dtypes.to_dict() == {'Name': np.dtype('O'), 'Age': np.dtype('int64')}
# True
注意,一个更稳妥的选择是使用 is_string_dtype
或 is_integer_dtype
:
assert (pd.api.types.is_string_dtype(df['Name']) and
pd.api.types.is_integer_dtype(df['Age'])
)
0
在Pandas中,字符串类型的列会被显示为数据类型 object
。
用你的例子来说:
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
print(df.dtypes)
输出结果是:
df.dtypes
Name object
Age int64
dtype: object
因为你要把这些数据加载到数据库表中,我想你应该是在使用 pandas.DataFrame.to_sql
这个函数。在这个函数里,dtype
这个选项会对你很有帮助,特别是在验证数据时。
根据Pandas的源代码:
指定数据类型(特别适用于有缺失值的整数)。注意,虽然Pandas被迫将数据存储为浮点数,但数据库支持可为空的整数。当用Python获取数据时,我们会得到整数标量。
>>> df = pd.DataFrame({"A": [1, None, 2]})
>>> df
A
0 1.0
1 NaN
2 2.0
>>> from sqlalchemy.types import Integer
>>> df.to_sql(name='integers', con=engine, index=False,
... dtype={"A": Integer()})
3
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM integers")).fetchall()
[(1,), (None,), (2,)]