Một lỗi vô tình hoặc cố ý trong một chương trình có thể ngăn chương trình hoạt động bình thường hoặc thậm chí làm hỏng dữ liệu. Vì vậy, làm thế nào bạn có thể kiểm tra?
Xác thực dữ liệu là khi một chương trình kiểm tra dữ liệu để đảm bảo dữ liệu đáp ứng một số quy tắc hoặc hạn chế. Có nhiều kiểm tra xác thực dữ liệu khác nhau có thể được thực hiện. Ví dụ: chúng tôi có thể kiểm tra xem dữ liệu
- Là loại dữ liệu chính xác, ví dụ như một số và không phải là một chuỗi
- Không có giá trị không hợp lệ, chẳng hạn như mã zip được cung cấp có một chữ cái
- Không nằm ngoài phạm vi, chẳng hạn như tuổi được cung cấp dưới dạng số âm hoặc có phép chia cho 0
- Đáp ứng các ràng buộc, ví dụ: ngày nhất định chỉ có thể là trong tương lai hoặc tin nhắn không vượt quá độ dài tối đa
- Nhất quán với các dữ liệu hoặc ràng buộc khác, ví dụ như điểm kiểm tra của học sinh và điểm viết của học sinh là nhất quán
- Là hợp lệ, chẳng hạn như tên tệp đã cho là dành cho một tệp hiện có
- Đã hoàn tất, chẳng hạn như đảm bảo tất cả các trường biểu mẫu bắt buộc đều có dữ liệu
Nơi chúng tôi kiểm tra dữ liệu phụ thuộc vào chương trình, nhưng đây là một số manh mối
- Bất cứ khi nào chúng tôi nhận được đầu vào trực tiếp từ người dùng, hãy kiểm tra loại dữ liệu và phạm vi hợp lệ
- Khi mã của chúng tôi được chứa trong thư viện nơi mọi người có thể sử dụng mã, hãy kiểm tra tất cả đầu vào cho tất cả các phương thức để người gọi không thể làm hỏng hoặc phá vỡ mã của chúng tôi
- Bất cứ khi nào người gọi thay đổi thuộc tính lớp, hãy kiểm tra để đảm bảo rằng giá trị có thể thay đổi và giá trị mới hợp lệ
Đã xảy ra lỗi khi tải video này
Hãy thử làm mới trang hoặc liên hệ với bộ phận hỗ trợ khách hàng
Bạn phải cC tạo một tài khoản để tiếp tục xem
Đăng ký để xem bài học này
Bạn là học sinh hay giáo viên?
tôi là học sinh tôi là giáo viên
Tạo tài khoản của bạn để tiếp tục xem
Là thành viên, bạn cũng sẽ có quyền truy cập không giới hạn vào hơn 84.000 bài học về toán, tiếng Anh, khoa học, lịch sử, v.v. Ngoài ra, nhận các bài kiểm tra thực hành, câu đố và huấn luyện được cá nhân hóa để giúp bạn thành công
Nhận quyền truy cập không giới hạn vào hơn 84.000 bài học
Chỉ mất vài phút để thiết lập và bạn có thể hủy bất cứ lúc nào
Đã đăng ký?Tài nguyên do giáo viên tạo ra cho giáo viên
Hơn 30.000 bài học video & tài nguyên giảng dạy‐tất cả ở một nơi.
bài học video
Câu đố và Bảng tính
Tích hợp lớp học
kế hoạch bài học
Tôi chắc chắn sẽ giới thiệu Study. com đến các đồng nghiệp của tôi. Nó giống như một giáo viên vung cây đũa thần và làm việc cho tôi. Tôi cảm thấy như đó là một cứu cánh
Tulsi
nuốt không tải
Bài đăng. 2
Chủ đề. 1
Đã tham gia. Tháng 7 năm 2018
Danh tiếng. 0
17-Jul-2018, 11. 16 giờ sáng [Bài đăng này đã được sửa đổi lần cuối. 17-07-2018, 11. 43 giờ sáng bởi Tulsi. ]Xin chào Techie,
ai đó có thể vui lòng giúp tôi cách thực hiện Tự động hóa xác thực dữ liệu bằng Python
nguồn của tôi là SQL SERVER và Target là SNOWFLAKE. tôi đang sử dụng informatica để tải dữ liệu từ nguồn [sql]
để nhắm mục tiêu bông tuyết
có thể ai đó nếu có thể vui lòng chia sẻ chuyên môn của họ, cách tiếp cận theo cách python
Cảm ơn rất nhiều
Ý tưởng của tôi là chuyển ngày làm tham số để so sánh số lượng nguồn và mục tiêunó sẽ là một cái gì đó như thế này
1. Thiết lập kết nối với bông tuyết
2. Kết nối được thiết lập với Nguồn
hai tham số. Tham số sửa đổi lần cuối hoặc CreatedDatetime. Giá trị cung cấp cho 2 tham số này
Dựa trên giá trị Tham số, tổng số bản ghi sẽ tìm nạp và lưu trữ trong mảng[x] cho Nguồn Và Mảng [Y]
cho mục tiêu
So sánh 2 và lưu kết quả trong bảng trong sql với cột, tham số và Count Diff của src và target
Thách thức ở đây là làm thế nào để kết nối với snowflake và sql
Ai đó có thể vui lòng chia sẻ chuyên môn của họ với một số cách khác
Thanks
Hồi đáp
Tìm thấy
Hồi đáp
Các vấn đề về kiểu dữ liệu là một trong những mối quan tâm lớn nhất khi xử lý dữ liệu trong python. Nếu bạn đang tự hỏi làm thế nào để
Đảm bảo rằng một cột thuộc loại dữ liệu cụ thể [ e. g. một cột int không có những thứ như dấu phẩy, khoảng trắng, v.v.]
Đảm bảo các loại dữ liệu chính xác trong python, trước khi chèn chúng vào cơ sở dữ liệu
Sau đó, bài viết này là dành cho bạn. Trong bài đăng này, chúng tôi xem cách phân tích dữ liệu thành các loại dữ liệu dự kiến bằng python gốc. Sau đó, chúng ta sẽ xem cách chúng ta có thể xây dựng mẫu phân tích kiểu dữ liệu có thể sử dụng lại bằng cách sử dụng pydantic
Lưu ý rằng có một sự khác biệt chính giữa phân tích cú pháp và xác thực. Phân tích cú pháp đề cập đến việc chuyển đổi dữ liệu thành một loại dữ liệu cụ thể. Xác thực đề cập đến việc kiểm tra xem một đầu vào đã cho có thuộc một loại nhất định hay không
int['123'] # parsing
123
isinstance['123', int] # validating
False
Trong bài đăng này, chúng tôi sử dụng thuật ngữ xác thực có nghĩa là dữ liệu có thể được phân tích thành một loại dự kiến
Sử dụng Python bản địa
Giả sử bạn đang xử lý một số dữ liệu tiếp thị. Tập dữ liệu chứa id người dùng, tên, số tiền đã chi tiêu và trạng thái người dùng. Mục tiêu là để
- Chuyển đổi tên người dùng thành chữ thường
- Chuyển đổi số tiền chi tiêu thành giá trị thập phân
- Đảm bảo rằng giá trị trạng thái thuộc về một trong số
ACTIVE
hoặcINACTIVE
hoặcSUSPENDED
- Chuyển đổi các hàng thành các hàng JSON
Bạn có thể làm một cái gì đó như
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
Bạn có thể thấy cách xác thực và phân tích cú pháp dữ liệu được kết hợp với xử lý dữ liệu[e. g. Hàm
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
0]. Điều này cũng sẽ liên quan đến việc viết rất nhiều logic from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
1 để phát hiện bất kỳ lỗi phân tích cú pháp nào. Hãy thử chạy vòng lặp for được hiển thị ở trên với dữ liệu nàymarketing_data = [
'uid,user_name,amount_spent,status',
'1,person1,x,ACTIVE',
]
Bạn sẽ nhận được một
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
2 và phải sử dụng một khối from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
1 hoặc logic có điều kiện để nắm bắt những vấn đề này. Mặc dù điều này là có thể, nhưng việc xác thực các loại dữ liệu theo cách thủ công và xử lý tất cả các trường hợp như vậy có thể trở nên khó khănSử dụng Pydantic
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 là một thư viện phổ biến phân tích dữ liệu của chúng tôi thành các loại dữ liệu dự kiến. Chúng tôi có thể xác định kiểu dữ liệu của mình bằng cách sử dụng from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
5 và để from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 xử lý phân tích kiểu dữ liệu. Hãy xem cách chúng tôi sẽ xử lý dữ liệu tiếp thị của mìnhpip install pydantic
import json
import logging
from decimal import Decimal, InvalidOperation
from enum import Enum
from typing import Any, Optional
from pydantic import ValidationError
from pydantic.dataclasses import dataclass
from pydantic.json import pydantic_encoder
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,x,ACTIVE',
'7,person7,200,',
]
# status can only be one of these 3
class StatusType[Enum]:
ACTIVE = 'ACTIVE'
INACTIVE = 'INACTIVE'
SUSPENDED = 'SUSPENDED'
# amount needs its own custom data type
# ref: //pydantic-docs.helpmanual.io/usage/types/#custom-data-types
class ExcelNumber:
@classmethod
def __get_validators__[cls]:
yield cls.validate
@classmethod
def validate[cls, v: Any] -> Optional[Decimal]:
if v is not None and str[v] != '':
try:
return Decimal[
str[v]
.replace[',', '']
.replace['$', '']
.replace['USD', '']
.strip[]
]
except InvalidOperation as io:
logging.error[
f'Error while parsing {str[v]} to decimal. Error: {io}'
]
raise ValidationError
return None
@dataclass
class MarketData:
uid: int
user_name: str
amount_spent: Optional[
ExcelNumber
] # optional means that this field can be None
status: StatusType
error_count = 0
output_data = []
for idx, d in enumerate[marketing_data[1:]]:
try:
market_data = MarketData[*d.split[',']]
market_data.user_name = market_data.user_name.lower[]
output_data.append[json.dumps[market_data, default=pydantic_encoder]]
except ValidationError as ve:
logging.error[f'row number: {idx + 1}, row: {d}, error: {ve}']
error_count += 1
print[f'Error count: {error_count}']
print[output_data]
Bạn có thể thấy các sự cố xác thực xảy ra đối với hàng 6 và 7 từ nhật ký lỗi
ERROR:root:Error while parsing x to decimal. Error: []
ERROR:root:row number: 6, row: 6,person6,x,ACTIVE, error: 1 validation error for MarketData
amount_spent
__init__[] takes exactly 3 positional arguments [1 given] [type=type_error]
ERROR:root:row number: 7, row: 7,person7,200,, error: 1 validation error for MarketData
status
value is not a valid enumeration member; permitted: 'ACTIVE', 'INACTIVE', 'SUSPENDED' [type=type_error.enum; enum_values=[, , ]]
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 giúp bạn dễ dàng- Xác định loại dữ liệu cho tập dữ liệu của chúng tôi
- Phân tích cú pháp dữ liệu để khớp với các kiểu dữ liệu đã xác định
- Bắt lỗi kiểu dữ liệu với
8from decimal import Decimal # assume data from some data source marketing_data = [ 'uid,user_name,amount_spent,status', '1,PeRSON1,100,ACTIVE', '2,persOn2,100 USD,INACTIVE', '3,persON3,100$,SUSPENDED', '4,peRson4,10000.10,ACTIVE', '5,PERson5,,ACTIVE', '6,person6,20,ACTIVE', ] output_data = [] for d in marketing_data[1:]: uid, user_name, amount_spent, status = d.split[','] clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[] op_amt = Decimal[clean_amt] if clean_amt else None clean_status = [ status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None ] output_data.append[ { 'uid': uid, 'user_name': user_name.lower[], 'amount_spent': op_amt, 'status': clean_status, } ] print[output_data]
- Xác định kiểu dữ liệu tùy chỉnh
- Bắt lỗi loại bằng cách sử dụng
9from decimal import Decimal # assume data from some data source marketing_data = [ 'uid,user_name,amount_spent,status', '1,PeRSON1,100,ACTIVE', '2,persOn2,100 USD,INACTIVE', '3,persON3,100$,SUSPENDED', '4,peRson4,10000.10,ACTIVE', '5,PERson5,,ACTIVE', '6,person6,20,ACTIVE', ] output_data = [] for d in marketing_data[1:]: uid, user_name, amount_spent, status = d.split[','] clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[] op_amt = Decimal[clean_amt] if clean_amt else None clean_status = [ status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None ] output_data.append[ { 'uid': uid, 'user_name': user_name.lower[], 'amount_spent': op_amt, 'status': clean_status, } ] print[output_data]
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 cung cấp rất nhiều tính năng. Bạn có thể tham khảo tài liệu đầy đủ của nó tại đâyHãy cẩn thận về Pydantic
Mặc dù
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 là một công cụ tuyệt vời, nhưng có một số lưu ý cần lưu ý- Có thể mất dữ liệu. Nếu bạn có dữ liệu được xác định là int và truyền vào số float, thì
4 sẽ chuyển số float này thành int, dẫn đến mất dữ liệu. Vui lòng đọc cái này để biết ví dụ. Xem chủ đề này để được giải thích từ tác giả của thư viện. Bạn có thể sử dụng Pydantic để ngăn chặn vấn đề nàyfrom decimal import Decimal # assume data from some data source marketing_data = [ 'uid,user_name,amount_spent,status', '1,PeRSON1,100,ACTIVE', '2,persOn2,100 USD,INACTIVE', '3,persON3,100$,SUSPENDED', '4,peRson4,10000.10,ACTIVE', '5,PERson5,,ACTIVE', '6,person6,20,ACTIVE', ] output_data = [] for d in marketing_data[1:]: uid, user_name, amount_spent, status = d.split[','] clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[] op_amt = Decimal[clean_amt] if clean_amt else None clean_status = [ status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None ] output_data.append[ { 'uid': uid, 'user_name': user_name.lower[], 'amount_spent': op_amt, 'status': clean_status, } ] print[output_data]
- Mô hình cơ sở v Lớp dữ liệu. Bạn có thể sử dụng
4 vớifrom decimal import Decimal # assume data from some data source marketing_data = [ 'uid,user_name,amount_spent,status', '1,PeRSON1,100,ACTIVE', '2,persOn2,100 USD,INACTIVE', '3,persON3,100$,SUSPENDED', '4,peRson4,10000.10,ACTIVE', '5,PERson5,,ACTIVE', '6,person6,20,ACTIVE', ] output_data = [] for d in marketing_data[1:]: uid, user_name, amount_spent, status = d.split[','] clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[] op_amt = Decimal[clean_amt] if clean_amt else None clean_status = [ status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None ] output_data.append[ { 'uid': uid, 'user_name': user_name.lower[], 'amount_spent': op_amt, 'status': clean_status, } ] print[output_data]
4 của nó hoặc sử dụngmarketing_data = [ 'uid,user_name,amount_spent,status', '1,person1,x,ACTIVE', ]
5 của nó. Mặc dù chúng tôi đã sử dụng lớp dữ liệu trong các ví dụ mã của mình ở trên, điều quan trọng là phải hiểu sự khác biệt giữa chúng. Đọc chủ đề này để biết thêm chi tiếtmarketing_data = [ 'uid,user_name,amount_spent,status', '1,person1,x,ACTIVE', ]
- Hiệu suất. Bạn đang tạo một đối tượng cho mỗi hàng. Điều này liên quan đến một số chi phí
Phần kết luận
Hy vọng bài viết này cung cấp cho bạn một ý tưởng hay về cách đảm bảo tính chính xác của kiểu dữ liệu trong dữ liệu của bạn. Đảm bảo đúng kiểu dữ liệu giúp bạn tránh các lỗi chuyển đổi kiểu dữ liệu không tương thích. Tóm lại, chúng ta đã thấy cách
- Xác định các loại dữ liệu dự kiến cho bất kỳ tập dữ liệu nào
- Tạo các loại dữ liệu tùy chỉnh
- Phân tích cú pháp dữ liệu đến để khớp với các loại dữ liệu dự kiến
Khi xử lý dữ liệu từ một nguồn có thể không phải lúc nào cũng có đúng loại dữ liệu, hãy thử
from decimal import Decimal
# assume data from some data source
marketing_data = [
'uid,user_name,amount_spent,status',
'1,PeRSON1,100,ACTIVE',
'2,persOn2,100 USD,INACTIVE',
'3,persON3,100$,SUSPENDED',
'4,peRson4,10000.10,ACTIVE',
'5,PERson5,,ACTIVE',
'6,person6,20,ACTIVE',
]
output_data = []
for d in marketing_data[1:]:
uid, user_name, amount_spent, status = d.split[',']
clean_amt = amount_spent.replace['$', ''].replace['USD', ''].strip[]
op_amt = Decimal[clean_amt] if clean_amt else None
clean_status = [
status if status in {'ACTIVE', 'INACTIVE', 'SUSPENDED'} else None
]
output_data.append[
{
'uid': uid,
'user_name': user_name.lower[],
'amount_spent': op_amt,
'status': clean_status,
}
]
print[output_data]
4 để phân tích dữ liệu thành các loại dữ liệu dự kiến. Bạn có thể tiết kiệm thời gian xử lý các trường hợp cạnh và giữ cho cơ sở mã của bạn sạch sẽ bằng cách tuân theo nguyên tắc DRY