《Python數據處理》9.1.1導入數據筆記:agate.exceptions.CastError: Can not parse value as Decimal. Error at row
成功去掉報錯後的截圖
一、報錯現象:
源碼:
def agate_data_check(self):
'''數據類型猜測,將xlrd數據類型轉爲agate數據類型'''
text_type = agate.Text()
number_type = agate.Number()
boolean_type = agate.Boolean()
date_type = agate.DataType()
example_row = self.xlrd_read_xls().row(6)
#示例
print(example_row)
print(example_row[0].ctype)#類型
print(example_row[0].value)
print(ctype_text)#這應當是一個固定的設置的字典
'''xlrd的數據類型'''
'''將xlrd的數據類型轉爲agate的數據類型'''
types = []
for v in example_row:
'''ctype_text爲字典'''
value_type = ctype_text[v.ctype]
#一個一個
#print(value_type, end=' ')
if value_type == 'text':
types.append(text_type)
elif value_type == 'number':
types.append(number_type)
elif value_type =='xldate':
types.append(date_type)
else:
types.append(text_type)
for type in types:
pass
#return types
#pprint.pprint(type)
'''導入agate表中'''
table = agate.Table(self.country_data(), self.combine_title(), types)#self.agate_data_check())
在此處進了函數封裝,基本內容與書上源碼一致,或許存在變量名有不一致的地方
運行後出現報錯
agate.exceptions.CastError: Can not parse value "" as Decimal. Error at row 1 column Place of residence (%) Urban.
而沒有出現書中所述的
CastError can not convert value '-' to Decimal for NumberColumn
即使進行清理
def get_new_array(self, clean_function):
new_arr = []
for row in self.country_data():
clean_row = [clean_function(rv) for rv in row]
new_arr.append(clean_row)
pprint.pprint(new_arr)
table = agate.Table(new_arr, self.combine_title(), self.agate_data_check()
#注:同上進行過封裝,所以titles變成了self.combine_title()
一樣的報錯
二、解決方法
由於與書中錯誤不同,所以自行解決問題
第一步:
最後一個報錯爲
agate.exceptions.CastError: Can not parse value "" as Decimal. Error at row 1 column Place of residence (%) Urban.
位於
File "D:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\agate\table\__init__.py", line 133, in __init__
raise CastError(str(e) + ' Error at row %s column %s.' % (i, self._column_names[j]))
找到這個文件,將except內容註釋掉
結果成功
注意:如果第一步未成功則進行第二步:
第二步:
首先,
(ps:在第一次如同第一步修改時,出現一樣的報錯即修改未成功,但是第二次只進行第一步時的修改時成功了,可能會需要先進行第二步)
agate.exceptions.CastError: Can not parse value "" as Decimal. Error at row
然後向上看上一個報錯:
agate.exceptions.CastError: Can not parse value "" as Decimal.
位於
註釋掉
結果contries and area爲空。
其次,去掉註釋進行還原
最後,回到第一步的修改方式
運行結果
三、疑惑
不知道爲什麼,其修改後成功的原理不明