2017-10-06 23 views
1

試圖使用Python和熊貓來驗證csv文件中的數據。提供乾淨的數據時一切正常。但是,當數據出現問題時,問題很難找到。提高任何形式的錯誤都會很好。這裏有一些僞代碼:如何驗證pandas.read_csv讀取的csv數據?

dtypes = {'Date': 'str', 'yesno': 'str', 'int_val': 'int', 'decimal_value': 'str'} 
df = pd.read_csv(filename, dtype=dtypes) 

# Ensure exceptions are thrown for invalid data. 

# valid date format in date. ValueError raised for invalid data. 
pd.to_datetime(df['Date']) 

# 'yes' or 'no' for the yesno field. (has to be in a list of values) 
# valid integer for int_val. 
# a valid integer or decimal number for decimal_value 

我甚至不確定pd.to_datetime是驗證日期的最佳方法。這樣做的好方法是什麼?

+0

一旦你發現無效數據,你想做什麼? –

+0

提高任何錯誤都很好。如果任何地方的日期格式無效,則pd.to_datetime(df ['Date'])語句會引發ValueError。 –

+0

然後,你有你的答案。 –

回答

1

對於yesno字段,'yes'或'no'。 (必須是在值的列表):

df.yesno.isin(['yes','no']).all() # Returns False if there are any other values 

爲int_val有效整數:

df.int_val.astype(int) # Throws an error if there are non-integers 
# or, if int_val are floats: 
import numpy as np 
np.isclose(df.int_val.round(0),df.int_val.astype(int)).all() 

有效的整數或十進制數爲decimal_value:

df.decimal_value.astype(float) # similar to above 

使用pd.to_datetime()驗證日期可能是最好的;你也可以根據需要指定日期的格式,例如關鍵字參數format = '%y-%m-%d'預計日期的格式爲yyyy-mm-dd

+0

謝謝。這很有幫助。 –

相關問題