{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "John Leung",
  "title_listed": "Simplifying the Python Code for Data Engineering Projects",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/",
  "publish_date": "2024-06-12",
  "corpus_stage": "",
  "notes": "",
  "id": "1e719a54c65f",
  "collected_at": "2026-10-02T04:23:32",
  "title": "Simplifying the Python Code for Data Engineering Projects | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# Simplifying the Python Code for Data Engineering Projects\nPython tricks and techniques for data ingestion, validation, processing, and testing: a practical walkthrough\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nJune 12, 202411 min read\nRaw data comes from various sources and formats. Before the data can be available to answer critical business questions, substantial effort and time are required to perform data engineering. While the underlying data infrastructure can vary based on the data volume, velocity, and analytics requirements, some fundamental code design techniques are still relevant to simplify and streamline various tasks across time.\nThis article will explore different critical parts of general data engineering projects, from data ingestion to pipeline testing. Python is the most widely used programming language for data engineering, and we will learn how to deal with these use cases using built-in functionalities and efficient libraries in Python.\n![Photo by Katerina Pavlyuchkova on Unsplash](../images/000.jpg)\nPhoto by [Katerina Pavlyuchkova](https://unsplash.com/@kat_katerina?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n* * *\nImagine you have an online retail shop that sells unique, all-occasion gifts. The online shop is so popular that it has a high volume of transactions every minute and second. You have the ambition to satisfy more current customers' needs and serve more new customers through analyzing buying habits about the current transactions, so this motivates you to dive into the data processing of the transaction records as the preparation.\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) and [Data Engineer](https://roadmap.sh/data-engineer) roadmaps.\n### 0 Mock data\nWe first mock some transaction data into a file using the [JSON Lines](https://jsonlines.org/) (JSONL) text format, where each line is a separate JSON object. This format is appealing for data streaming in areas, such as web/ app analytics and log management.\nIn our file, the data fields belong to various data types. They include the customer and product identifiers (in integer/ array format), the payment method (in string format), and the total transaction amount (in float number).\npython\n\n```\nimport json\nimport random\nimport numpy as np\nimport datetime\n\n# Remove existing 'retail_transactions.jsonl' file, if any\n! rm -f /p/a/t/h retail_transactions.jsonl\n\n# Set the no of transactions\nno_of_iteration = 500000\n\n# Open a file in write mode\nwith open('retail_transactions.jsonl', 'w') as f:\n  for num in range(no_of_iteration):\n    if (random.randint(1, 10000) != 5000):\n      # Create a valid transaction\n      new_txn = {\n        'orderID': num,\n        'customerID': random.randint(1, 100000),\n        'productID': np.random.randint(10000, size=random.randint(1, 5)).tolist(),\n        'paymentMthd': random.choice(['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']),\n        'totalAmt': round(random.random() * 5000, 2),\n        'invoiceTime': datetime.datetime.now().isoformat()\n      }\n    else:\n      # Create an invalid transaction\n      new_txn = {\n        'orderID': \"\",\n        'customerID': \"\",\n        'productID': \"\",\n        'paymentMthd': \"\",\n        'totalAmt': \"\",\n        'invoiceTime': \"\"\n       }\n\n     # Write the transaciton as a JSON line to the file\n     f.write(json.dumps(new_txn) + \"n\")\n```\n\nYou may discover several single transactions with blank data fields written to the file. This mimics the missing data issue, as one of the data quality issues often encountered in the real world.\n### 1 Data ingestion - Yield\nTo read the transaction records from the file, one of the simplest approaches is to loop through the dataset into a list and then convert it into a Pandas DataFrame.\nThis method will work like a charm for the 500,000 transactions in our demo dataset. But what if the real-world datasets range from millions to even billions of rows? We may sit still for long to wait until the whole computation completes, if not leading to memory issues.\nSometimes we don't care about the entire results and want to process the initial results instead before the last record is loaded. In such cases, we can alternatively use `yield` to control the flow of a [generator](https://wiki.python.org/moin/Generators).\n> The generator does not store the entire records in memory. Instead, it gives a value one at a time and pauses the function execution until the next value is requested.\nThere are routines of interleaving user codes with library codes. It also enforces sequencing, which means you cannot access the second record before reaching the first. You can learn more about this concept in the [Pydata talk video](https://www.youtube.com/watch?v=7lmCu8wz8ro), which provides a detailed explanation.\nThe yield statement has different practical usages. For example, we can go through each line of the file and yield only the non-blank records. Below shows how we can execute real-time data filtering:\npython\n\n```\nimport json\n\ndef read_json_file(file_name):\n  # Read the JSONL file\n  with open(file_name) as f:\n    for line in f:\n      txn = json.loads(line)\n      # Yield valid transactions only\n      if (txn['orderID'] != \"\"):\n        yield(txn)\n\ntxn_generator = read_json_file('retail_transactions.jsonl')\n```\n\nThe output of these codes gives a Python generator, a special type of iterator. You can use the `next` function in a loop to return the subsequent items one by one. Apart from real-time data filtering, another idea is to design a generator function that pre-processes data and yields it in a pre-defined batch size, which can be parsed straightforwardly to feed a machine-learning model for training. And more, we can use it to asynchronously handle web requests and responses, when crawling web pages.\n### 2 Data validation - Pydantic\nAssume you have a list of JSON data that covers the information of transaction records after data ingestion. Here is a sample transaction:\njson\n\n```\n{\n 'orderID': 10000,\n 'customerID': 48316,\n 'productID': [5620],\n 'paymentMthd': 'Cash on delivery',\n 'totalAmt': 9301.2,\n 'invoiceTime': '2024-06-10T23:30:29.608443',\n 'price': -1\n}\n```\n\nFor each incoming data, we want to ensure it is being validated, otherwise, we will easily hit different types of errors when running the subsequent data processing functions. This can be achieved using `pydantic` library.\n> We first define the schema of our data fields using the [Pydantic model](https://docs.pydantic.dev/latest/api/base_model/), then validate our JSON data using `model_validate()` function.\npython\n\n```\nfrom datetime import datetime\nfrom pydantic import BaseModel, ValidationError\n\n# Define the data model for a transaction record\nclass TxnModel(BaseModel):\n  orderID: int\n  customerID: int\n  productID: list[int]\n  paymentMthd: str\n  totalAmt: float\n  invoiceTime: datetime\n\ntry:\n  # Validate the sample case against the schema\n  TxnModel.model_validate(sample_txn)\n  print(\"Validated successfully!\")\nexcept ValidationError as exc:\n  # Print error messages for any validation error\n  print(\"Validation Error:\")\n  print(exc.errors())\n\n# Output:\n# Validated successfully\n```\n\nSometimes, we find the necessity to apply stricter validation rules. For example, the Pydantic base model attempts to coerce string data to an integer if possible. To avoid this, you can set `strict=True` at the model level or field level.\nBesides, we can apply custom validation rules to data fields. For example, we may want to check if the payment method value is within our expectations. To facilitate testing, we manually set the payment method of the sample case to 'Bitcoin', which is a non-existent option in the online shop, and then use `AfterValidator` to embed a function for further checking.\npython\n\n```\nfrom typing import Annotated\nfrom pydantic.functional_validators import AfterValidator\n\n# Customize the validation rule\ndef validate_payment_mthd(paymentMthd: str):\n  possible_values = ['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']\n  if paymentMthd not in possible_values:\n    raise ValueError(f\"Invalid paymentMthd, payment type must be one of {possible_values}\")\n  return storage\n\n# Define the data model for a transaction record\nclass TxnModel(BaseModel):\n  orderID: int = Field(strict=True)\n  customerID: int\n  productID: list[int]\n  paymentMthd: Annotated[str, AfterValidator(validate_payment_mthd)]\n  totalAmt: Annotated[float, Field(strict=True, gt=0)]\n  invoiceTime: datetime\n\n# Manually define a non-existent payment method\nsample_txn['paymentMthd'] = 'Bitcoin'\n\ntry:\n  # Validate the sample case against the schema\n  TxnModel.model_validate(sample_txn)\n  print(\"Validated successfully!\")\nexcept ValidationError as exc:\n  # Print error messages for any validation error\n  print(\"Validation Error:\")\n  print(exc.errors()[0]['ctx'])\n\n# Output\n# Validation Error:\n# {'error': ValueError(\"Invalid paymentMthd, payment type must be one of ['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']\")}\n```\n\nThe validator successfully identifies that the payment method is not within the list of possible values. This is done by applying Pydantic's inner validation logic, followed by custom validation functions. The code raises a `ValueError`, which populates `ValidationError`.\nWhen the error is triggered, we can have follow-up actions for rectification. These features help eliminate data errors, thus ensuring the accuracy and completeness of our data.\n### 3 Data processing\n(1) Python decorator\nAfter data validation, we start working with data-intensive functions. There is a high chance of encountering lengthy execution times as the data pipeline becomes complex. We wish to identify the root cause and optimize the time performance of functions. One simple method is to collect two timestamps at the beginning and end of every function, and then calculate the time differences one by one.\nTo ensure the code is less cluttered throughout the data pipeline, we can leverage the [Python decorator](https://book.pythontips.com/en/latest/decorators.html).\n> We first design a Python decorator that measures the execution time. Afterward, we annotate any function that requires this feature.\nFor example, you can measure the time taken to categorize prices for all transactions.\npython\n\n```\nimport time\n\n# Measure the excution time of a given function\ndef time_decorator(func):\n  def wrapper(*args, **kwargs):\n    begin_time = time.time()\n    output = func(*args, **kwargs)\n    end_time = time.time()\n    print(f\"Execution time of function {func.__name__}: {round(end_time - begin_time, 2)} seconds.\")\n    return output\n  return wrapper\n\n# Categorize the total amount of each transaction\n@time_decorator\ndef group_txn_price(data):\n  for txn in data:\n    price = txn['totalAmt']\n    if 0 <= price <= 1500:\n      txn['totalAmtCat'] = 'Low'\n    elif 1500 < price <= 3500:\n      txn['totalAmtCat'] = 'Moderate'\n    elif 3500 < price:\n      txn['totalAmtCat'] = 'High'\n    return data\n\ntxn_list = group_txn_price(txn_list)\n\n# Output\n# Execution time of function group_txn_price: 0.26 seconds.\n```\n\nThe decorator approach makes the code reusable without changing the source code of our original functions. Similarly, we can apply decorator ideas for logging function completion or email alerting when jobs encounter failure.\n(2) Map, reduce, filter\nThese are commonly used Python array methods that many developers may be familiar with. But I still think they are worth mentioning due to several reasons: (1) immutable - the functions do not modify values of the original lists; (2) the chain flexibility - can apply a combination of functions simultaneously; and (3) concise and readable - with only one line of code.\nAssume we have a list of JSON objects with only two keys: payment method and total amount. Let's explore some examples of how these functions work.\n**Map:** Perform the same operation on all elements in the list (e.g. adding a suffix to the values of the payment method).\npython\n\n```\nupdated_txn_list = list(map(lambda x: {\n                      'paymentMthd': f\"{x['paymentMthd']}_2024\",\n                      \"totalAmt\": x[\"totalAmt\"]\n                   }, txn_list))\n\nprint(updated_txn_list)\n\n# Output\n# [{'paymentMthd': 'Cryptocurrency_2024', 'totalAmt': 3339.85},\n# {'paymentMthd': 'Cash on delivery_2024', 'totalAmt': 872.52},\n# ...]\n```\n\n**Filter** : Obtain a subset of elements that meet a certain condition(s) (e.g. only records with cryptocurrency as the payment method).\npython\n\n```\nupdated_txn_list = list(map(lambda x: x, filter(lambda y: y[\"paymentMthd\"] == \"Cryptocurrency\", txn_list)))\n\nprint(updated_txn_list)\n\n# Output\n# [{'paymentMthd': 'Cryptocurrency', 'totalAmt': 3339.85},\n# {'paymentMthd': 'Cryptocurrency', 'totalAmt': 576.15},\n# ...]\n```\n\n**Reduce** : Get a single-valued outcome (e.g. summing or multiplying all elements).\npython\n\n```\nfrom functools import reduce\n\ntotal_amt_crypto = reduce(lambda acc, x: acc + x[\"totalAmt\"], updated_txn_list, 0)\n\nprint(total_amt_crypto)\n\n# Output\n# 250353984.67000002\n```\n\nWe can leverage these functions during the transformation steps in data science projects. For example, use `map()` to scale or normalize the data, use `filter()` to remove outliers and irrelevant data points, and `reduce()` to generate summary statistics.\n### 4 Data pipeline testing - Pytest\nData pipelines often involve data ingestion, data cleansing, and Extract-Transform-Load (ETL) operations. The scope of potential errors can be broad and easily overlooked, especially as the model flow and result are hard for users to interpret. This leads to a heavier reliance on testing efforts by the development team.\n> It is common to conduct unit testing to ascertain each component of the machine learning system performs as expected.\nOne of the most popular Python testing frameworks is `[Pytest](https://docs.pytest.org/en/stable/contents.html)`. Imagine we want to ensure the high-quality of transformed data that both technical teams and decision-makers can trust. We can test for the function that we have gone through about categorizing transaction prices. To achieve this, we need to prepare two Python files:\n  * **feature_engineering.py** : The file containing the previously built function\n\n\npython\n\n```\n# Categorize the total amount of each transaction\ndef add_features(sample_cases):\n  for txn in sample_cases:\n    price = txn['totalAmt']\n  if 0 <= price <= 1500:\n    txn['totalAmtCat'] = 'Low'\n  elif 1500 < price <= 3500:\n    txn['totalAmtCat'] = 'Moderate'\n  elif 3500 < price:\n    txn['totalAmtCat'] = 'High'\n\nreturn sample_cases\n```\n\n  * **test_feature_engineering.py** : The file with the \"test_\" prefix, which Pytest will recognize for testing purposes only.\n\n\npython\n\n```\nfrom feature_engineering import add_features\n\ndef test_add_features():\n  sample_cases = [{\n      'orderID': 1,\n      'customerID': 36536,\n      'productID': [2209, 2262, 4912, 3162, 5734],\n      'paymentMthd': 'Cryptocurrency',\n      'totalAmt': 576.15,\n      'invoiceTime': '2024–06–10T23:53:25.329928'\n    }]\n\n  # Call the function with the sample cases\n  sample_cases = add_features(sample_cases)\n\n  # Check the assertations\n  for txn in sample_cases: \n    assert 'totalAmtCat' in list(txn.keys())\n    assert len(txn) == 7\n    assert len(txn['totalAmtCat']) != 0\n```\n\nThe assert statements above ensure that the new 'totalAmtCat' data field is added with a non-blank value, and the original data fields are not affected. By executing the command `Pytest`, we can know that our test has passed!\n![Pytest result - Test passed \\(Image by author\\)](../images/001.png)\nPytest result - Test passed (Image by author)\nFor a more advanced case, let's say we have three functions with the following sequences: `load_data`, `clean_data`, and `add_features`. How should we design the test file to validate the output of these functions one by one?\npython\n\n```\nimport pytest\nimport json\nfrom feature_engineering import load_data, clean_data, add_features\n\n# Set up a temporary JSONL file\n@pytest.fixture\ndef jsonl_file(tmp_path):\n  sample_cases = [{'orderID': 10000,\n    'customerID': 48316,\n    'productID': [5620],\n    'paymentMthd': 'Cash on delivery',\n    'totalAmt': 9301.2,\n    'invoiceTime': '2024-06-10T23:30:29.608443',\n    'price': -1\n  }]\n\n  file_path = tmp_path + \"/test_transactions.jsonl\"\n\n  with open(file_path, 'w') as f:\n    for txn in sample_cases:\n        f.write(json.dumps(txn) + \"n\")\n\n  return file_path\n\n# Test function to validate the `load_data` function\ndef test_load_data(jsonl_file):\n  data = load_data(jsonl_file)\n  # assert statements here\n\n# Test function to validate the `clean_data` function\ndef test_clean_data(jsonl_file):\n  data = load_data(jsonl_file)\n  data = clean_data(data)\n  # assert statements here\n\n# Test function to validate the `add_features` function\ndef test_add_features(jsonl_file):\n  data = load_data(jsonl_file)\n  data = clean_data(data)\n  data = add_features(data)\n  # assert statements here\n```\n\nWe should define a fixed baseline for initialization, such as a JSON Lines file with sample test cases. Here we use `@pytest.fixture`decorator, which works similarly to the `time_decorator`we discussed earlier in the Python decorator section. This decorator helps prevent repeatedly initializing the sample files. For the remaining codes, we involve several test functions to run the pipeline functions and use assert statements to detect logical errors.\n* * *\n### Wrapping it up\nWe came across several critical aspects of data engineering projects, and explored how to simplify and streamline the Python code for efficiency and readability:\n  * Data ingestion, by using `yield` to process large datasets with efficient memory usage.\n  * Data validation, by leveraging `Pydantic` to validate data fields based on schema and customized value patterns.\n  * Data processing, by applying Python decorator and built-in libraries to enable additional functionalities without repeated codes.\n  * Pipeline testing, by using `Pytest` to ensure high-quality function outputs throughout the workflow.\n\n\n* * *\n### Before you go\nIf you enjoy this reading, I invite you to **** follow my [Medium page](https://medium.com/@johnleungTJ) and [LinkedIn page](https://www.linkedin.com/in/john-leung-639800115/). By doing so, you can stay updated with exciting content related to data science side projects, Machine Learning Operations (MLOps) demonstrations, and project management methodologies.\n> [**Performing Customer Analytics with LangChain and LLMs**](https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5)\n> [**Feature Engineering for Time-Series Using PySpark on Databricks**](https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-4766f66da8cde6940868.jpeg)\nWritten By\n## [John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[See all from John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[Big Data](https://towardsdatascience.com/tag/big-data/)[Data Engineering](https://towardsdatascience.com/tag/data-engineering/)[Programming](https://towardsdatascience.com/tag/programming/)[Python](https://towardsdatascience.com/tag/python/)[Tips And Tricks](https://towardsdatascience.com/tag/tips-and-tricks/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&title=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&title=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&text=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpg)](https://towardsdatascience.com/how-to-read-and-write-data-from-to-the-same-quip-spreadsheet-using-quip-apis-in-python-48f4db96bf72/)\n## [How to Read and Write Data from/to the Quip Spreadsheet using Quip Python APIs](https://towardsdatascience.com/how-to-read-and-write-data-from-to-the-same-quip-spreadsheet-using-quip-apis-in-python-48f4db96bf72/)\n[](https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/)\nEnable end-users to provide their inputs that can then be used as overrides/additional context in the final analytical solution\n[Isha Garg](https://towardsdatascience.com/author/ishagarg2010/)\nNovember 17, 20237 min read\n  * [![](../images/003.jpeg)](https://towardsdatascience.com/behind-the-scenes-delta-lake-clones-d3578cff76a9/)\n## [Behind the scenes: Delta Lake Clones](https://towardsdatascience.com/behind-the-scenes-delta-lake-clones-d3578cff76a9/)\n[Programming](https://towardsdatascience.com/category/programming/)\nHow to clone your delta lake tables easily using Spark.\n[Prashanth Xavier](https://towardsdatascience.com/author/xavier211192/)\nMarch 14, 20215 min read\n  * [![](../images/004.jpg)](https://towardsdatascience.com/python-pandas-reading-a-csv-7865a11939fd/)\n## [Python Pandas Reading a CSV](https://towardsdatascience.com/python-pandas-reading-a-csv-7865a11939fd/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLearn how to read a CSV file and create a Pandas DataFrame\n[Dean McGrath](https://towardsdatascience.com/author/deanmcgrath/)\nFebruary 2, 20218 min read\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/a-practical-guide-on-missing-values-with-pandas-8fb3e0b46c24/)\n## [A Practical Guide on Missing Values with Pandas](https://towardsdatascience.com/a-practical-guide-on-missing-values-with-pandas-8fb3e0b46c24/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA comprehensive guide to handle missing\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJune 13, 20205 min read\n  * [![](../images/006.jpeg)](https://towardsdatascience.com/practical-guide-for-virtual-environments-in-python-b59bd5fe8f1/)\n## [Practical Guide for Virtual Environments in Python](https://towardsdatascience.com/practical-guide-for-virtual-environments-in-python-b59bd5fe8f1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUsing virtualenv and pipenv tools\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJanuary 3, 20214 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/a-gentle-introduction-to-self-training-and-semi-supervised-learning-ceee73178b38/)\n## [A Gentle Introduction to Self-Training and Semi-Supervised Learning](https://towardsdatascience.com/a-gentle-introduction-to-self-training-and-semi-supervised-learning-ceee73178b38/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCoding an example of self-training in Python to utilize unlabeled data for classification\n[Doug Steen](https://towardsdatascience.com/author/douglaspsteen/)\nAugust 30, 20208 min read\n  * [![](../images/008.jpeg)](https://towardsdatascience.com/hashicorp-vault-airflow-cfdddab31ea/)\n## [How To Setup HashiCorp Vault with Airflow](https://towardsdatascience.com/hashicorp-vault-airflow-cfdddab31ea/)\n[Programming](https://towardsdatascience.com/category/programming/)\nIntegrating HashiCorp Vault with Apache Airflow\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJune 3, 20224 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/surviving-a-coding-bootcamp-2963915e2285/)\n## [Surviving a Coding Bootcamp](https://towardsdatascience.com/surviving-a-coding-bootcamp-2963915e2285/)\n[Programming](https://towardsdatascience.com/category/programming/)\nTips, Tricks, and Advice from a Coding Bootcamp Survivor\n[Jesse Neumann](https://towardsdatascience.com/author/jesse989/)\nJuly 22, 20208 min read\n  * [![](../images/010.jpeg)](https://towardsdatascience.com/apache-hadoop-a-review-on-security-issues-and-solutions-for-hdfs-5ba06861b7cd/)\n## [Apache Hadoop: A Review on Security Issues and Solutions for HDFS](https://towardsdatascience.com/apache-hadoop-a-review-on-security-issues-and-solutions-for-hdfs-5ba06861b7cd/)\n[Security](https://towardsdatascience.com/category/technology/security/)\nBig Data Solution A deep dive into the security issues that occur in HDFS structure,...\n[KahEm Chu](https://towardsdatascience.com/author/kahemchu/)\nDecember 4, 202015 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Simplifying the Python Code for Data Engineering Projects | Towards Data Science",
    "description": "Python tricks and techniques for data ingestion, validation, processing, and testing: a practical walkthrough",
    "keywords": null,
    "author": "John Leung",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Simplifying the Python Code for Data Engineering Projects",
    "og:description": "Python tricks and techniques for data ingestion, validation, processing, and testing: a practical walkthrough",
    "og:url": "https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/06/0ZSZ-ePC8ZKm0IVY3-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1707",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "John Leung",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2024-06-12T06:09:04.000Z",
    "article:modified_time": "2024-06-12T06:09:04.000Z",
    "article:author": "https://towardsdatascience.com/author/johnleungtj/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_000.txt",
      "chars": 1156
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_001.txt",
      "chars": 296
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_002.txt",
      "chars": 183
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_003.txt",
      "chars": 567
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_004.txt",
      "chars": 1271
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_005.txt",
      "chars": 797
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_006.txt",
      "chars": 356
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_007.txt",
      "chars": 266
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_008.txt",
      "chars": 169
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_009.txt",
      "chars": 332
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_010.txt",
      "chars": 566
    },
    {
      "language": "txt",
      "file": "attachments/1e719a54c65f/code/block_011.txt",
      "chars": 1085
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:02:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:02:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:02:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:02:35Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/watch?v=7lmCu8wz8ro",
      "status": "ok",
      "local_path": "attachments/1e719a54c65f/videos/7lmCu8wz8ro.mp4",
      "bytes": 243459090,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "6722.081000"
    },
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/johnleungtj/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/big-data/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/tips-and-tricks/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-read-and-write-data-from-to-the-same-quip-spreadsheet-using-quip-apis-in-python-48f4db96bf72/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ishagarg2010/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/behind-the-scenes-delta-lake-clones-d3578cff76a9/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/xavier211192/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@kat_katerina"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/data-engineer"
    },
    {
      "type": "external",
      "href": "https://jsonlines.org/"
    },
    {
      "type": "external",
      "href": "https://wiki.python.org/moin/Generators"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/watch?v=7lmCu8wz8ro"
    },
    {
      "type": "external",
      "href": "https://docs.pydantic.dev/latest/api/base_model/"
    },
    {
      "type": "external",
      "href": "https://book.pythontips.com/en/latest/decorators.html"
    },
    {
      "type": "external",
      "href": "https://medium.com/@johnleungTJ"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/john-leung-639800115/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Simplifying+the+Python+Code+for+Data+Engineering+Projects&u=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Simplifying+the+Python+Code+for+Data+Engineering+Projects&url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Simplifying+the+Python+Code+for+Data+Engineering+Projects&url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:31:02Z",
  "source_url": "https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [
    {
      "local_path": "attachments/1e719a54c65f/videos/7lmCu8wz8ro.mp4",
      "bytes": 243459090,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "6722.081000",
      "status": "ok"
    }
  ],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# Simplifying the Python Code for Data Engineering Projects\nPython tricks and techniques for data ingestion, validation, processing, and testing: a practical walkthrough\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nJune 12, 202411 min read\nRaw data comes from various sources and formats. Before the data can be available to answer critical business questions, substantial effort and time are required to perform data engineering. While the underlying data infrastructure can vary based on the data volume, velocity, and analytics requirements, some fundamental code design techniques are still relevant to simplify and streamline various tasks across time.\nThis article will explore different critical parts of general data engineering projects, from data ingestion to pipeline testing. Python is the most widely used programming language for data engineering, and we will learn how to deal with these use cases using built-in functionalities and efficient libraries in Python.\n![Photo by Katerina Pavlyuchkova on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/06/0ZSZ-ePC8ZKm0IVY3-scaled.jpg)\nPhoto by [Katerina Pavlyuchkova](https://unsplash.com/@kat_katerina?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n* * *\nImagine you have an online retail shop that sells unique, all-occasion gifts. The online shop is so popular that it has a high volume of transactions every minute and second. You have the ambition to satisfy more current customers' needs and serve more new customers through analyzing buying habits about the current transactions, so this motivates you to dive into the data processing of the transaction records as the preparation.\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) and [Data Engineer](https://roadmap.sh/data-engineer) roadmaps.\n### 0 Mock data\nWe first mock some transaction data into a file using the [JSON Lines](https://jsonlines.org/) (JSONL) text format, where each line is a separate JSON object. This format is appealing for data streaming in areas, such as web/ app analytics and log management.\nIn our file, the data fields belong to various data types. They include the customer and product identifiers (in integer/ array format), the payment method (in string format), and the total transaction amount (in float number).\npython\n\n```\nimport json\nimport random\nimport numpy as np\nimport datetime\n\n# Remove existing 'retail_transactions.jsonl' file, if any\n! rm -f /p/a/t/h retail_transactions.jsonl\n\n# Set the no of transactions\nno_of_iteration = 500000\n\n# Open a file in write mode\nwith open('retail_transactions.jsonl', 'w') as f:\n  for num in range(no_of_iteration):\n    if (random.randint(1, 10000) != 5000):\n      # Create a valid transaction\n      new_txn = {\n        'orderID': num,\n        'customerID': random.randint(1, 100000),\n        'productID': np.random.randint(10000, size=random.randint(1, 5)).tolist(),\n        'paymentMthd': random.choice(['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']),\n        'totalAmt': round(random.random() * 5000, 2),\n        'invoiceTime': datetime.datetime.now().isoformat()\n      }\n    else:\n      # Create an invalid transaction\n      new_txn = {\n        'orderID': \"\",\n        'customerID': \"\",\n        'productID': \"\",\n        'paymentMthd': \"\",\n        'totalAmt': \"\",\n        'invoiceTime': \"\"\n       }\n\n     # Write the transaciton as a JSON line to the file\n     f.write(json.dumps(new_txn) + \"n\")\n```\n\nYou may discover several single transactions with blank data fields written to the file. This mimics the missing data issue, as one of the data quality issues often encountered in the real world.\n### 1 Data ingestion - Yield\nTo read the transaction records from the file, one of the simplest approaches is to loop through the dataset into a list and then convert it into a Pandas DataFrame.\nThis method will work like a charm for the 500,000 transactions in our demo dataset. But what if the real-world datasets range from millions to even billions of rows? We may sit still for long to wait until the whole computation completes, if not leading to memory issues.\nSometimes we don't care about the entire results and want to process the initial results instead before the last record is loaded. In such cases, we can alternatively use `yield` to control the flow of a [generator](https://wiki.python.org/moin/Generators).\n> The generator does not store the entire records in memory. Instead, it gives a value one at a time and pauses the function execution until the next value is requested.\nThere are routines of interleaving user codes with library codes. It also enforces sequencing, which means you cannot access the second record before reaching the first. You can learn more about this concept in the [Pydata talk video](https://www.youtube.com/watch?v=7lmCu8wz8ro), which provides a detailed explanation.\nThe yield statement has different practical usages. For example, we can go through each line of the file and yield only the non-blank records. Below shows how we can execute real-time data filtering:\npython\n\n```\nimport json\n\ndef read_json_file(file_name):\n  # Read the JSONL file\n  with open(file_name) as f:\n    for line in f:\n      txn = json.loads(line)\n      # Yield valid transactions only\n      if (txn['orderID'] != \"\"):\n        yield(txn)\n\ntxn_generator = read_json_file('retail_transactions.jsonl')\n```\n\nThe output of these codes gives a Python generator, a special type of iterator. You can use the `next` function in a loop to return the subsequent items one by one. Apart from real-time data filtering, another idea is to design a generator function that pre-processes data and yields it in a pre-defined batch size, which can be parsed straightforwardly to feed a machine-learning model for training. And more, we can use it to asynchronously handle web requests and responses, when crawling web pages.\n### 2 Data validation - Pydantic\nAssume you have a list of JSON data that covers the information of transaction records after data ingestion. Here is a sample transaction:\njson\n\n```\n{\n 'orderID': 10000,\n 'customerID': 48316,\n 'productID': [5620],\n 'paymentMthd': 'Cash on delivery',\n 'totalAmt': 9301.2,\n 'invoiceTime': '2024-06-10T23:30:29.608443',\n 'price': -1\n}\n```\n\nFor each incoming data, we want to ensure it is being validated, otherwise, we will easily hit different types of errors when running the subsequent data processing functions. This can be achieved using `pydantic` library.\n> We first define the schema of our data fields using the [Pydantic model](https://docs.pydantic.dev/latest/api/base_model/), then validate our JSON data using `model_validate()` function.\npython\n\n```\nfrom datetime import datetime\nfrom pydantic import BaseModel, ValidationError\n\n# Define the data model for a transaction record\nclass TxnModel(BaseModel):\n  orderID: int\n  customerID: int\n  productID: list[int]\n  paymentMthd: str\n  totalAmt: float\n  invoiceTime: datetime\n\ntry:\n  # Validate the sample case against the schema\n  TxnModel.model_validate(sample_txn)\n  print(\"Validated successfully!\")\nexcept ValidationError as exc:\n  # Print error messages for any validation error\n  print(\"Validation Error:\")\n  print(exc.errors())\n\n# Output:\n# Validated successfully\n```\n\nSometimes, we find the necessity to apply stricter validation rules. For example, the Pydantic base model attempts to coerce string data to an integer if possible. To avoid this, you can set `strict=True` at the model level or field level.\nBesides, we can apply custom validation rules to data fields. For example, we may want to check if the payment method value is within our expectations. To facilitate testing, we manually set the payment method of the sample case to 'Bitcoin', which is a non-existent option in the online shop, and then use `AfterValidator` to embed a function for further checking.\npython\n\n```\nfrom typing import Annotated\nfrom pydantic.functional_validators import AfterValidator\n\n# Customize the validation rule\ndef validate_payment_mthd(paymentMthd: str):\n  possible_values = ['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']\n  if paymentMthd not in possible_values:\n    raise ValueError(f\"Invalid paymentMthd, payment type must be one of {possible_values}\")\n  return storage\n\n# Define the data model for a transaction record\nclass TxnModel(BaseModel):\n  orderID: int = Field(strict=True)\n  customerID: int\n  productID: list[int]\n  paymentMthd: Annotated[str, AfterValidator(validate_payment_mthd)]\n  totalAmt: Annotated[float, Field(strict=True, gt=0)]\n  invoiceTime: datetime\n\n# Manually define a non-existent payment method\nsample_txn['paymentMthd'] = 'Bitcoin'\n\ntry:\n  # Validate the sample case against the schema\n  TxnModel.model_validate(sample_txn)\n  print(\"Validated successfully!\")\nexcept ValidationError as exc:\n  # Print error messages for any validation error\n  print(\"Validation Error:\")\n  print(exc.errors()[0]['ctx'])\n\n# Output\n# Validation Error:\n# {'error': ValueError(\"Invalid paymentMthd, payment type must be one of ['Credit card', 'Debit card', 'Digital wallet', 'Cash on delivery', 'Cryptocurrency']\")}\n```\n\nThe validator successfully identifies that the payment method is not within the list of possible values. This is done by applying Pydantic's inner validation logic, followed by custom validation functions. The code raises a `ValueError`, which populates `ValidationError`.\nWhen the error is triggered, we can have follow-up actions for rectification. These features help eliminate data errors, thus ensuring the accuracy and completeness of our data.\n### 3 Data processing\n(1) Python decorator\nAfter data validation, we start working with data-intensive functions. There is a high chance of encountering lengthy execution times as the data pipeline becomes complex. We wish to identify the root cause and optimize the time performance of functions. One simple method is to collect two timestamps at the beginning and end of every function, and then calculate the time differences one by one.\nTo ensure the code is less cluttered throughout the data pipeline, we can leverage the [Python decorator](https://book.pythontips.com/en/latest/decorators.html).\n> We first design a Python decorator that measures the execution time. Afterward, we annotate any function that requires this feature.\nFor example, you can measure the time taken to categorize prices for all transactions.\npython\n\n```\nimport time\n\n# Measure the excution time of a given function\ndef time_decorator(func):\n  def wrapper(*args, **kwargs):\n    begin_time = time.time()\n    output = func(*args, **kwargs)\n    end_time = time.time()\n    print(f\"Execution time of function {func.__name__}: {round(end_time - begin_time, 2)} seconds.\")\n    return output\n  return wrapper\n\n# Categorize the total amount of each transaction\n@time_decorator\ndef group_txn_price(data):\n  for txn in data:\n    price = txn['totalAmt']\n    if 0 <= price <= 1500:\n      txn['totalAmtCat'] = 'Low'\n    elif 1500 < price <= 3500:\n      txn['totalAmtCat'] = 'Moderate'\n    elif 3500 < price:\n      txn['totalAmtCat'] = 'High'\n    return data\n\ntxn_list = group_txn_price(txn_list)\n\n# Output\n# Execution time of function group_txn_price: 0.26 seconds.\n```\n\nThe decorator approach makes the code reusable without changing the source code of our original functions. Similarly, we can apply decorator ideas for logging function completion or email alerting when jobs encounter failure.\n(2) Map, reduce, filter\nThese are commonly used Python array methods that many developers may be familiar with. But I still think they are worth mentioning due to several reasons: (1) immutable - the functions do not modify values of the original lists; (2) the chain flexibility - can apply a combination of functions simultaneously; and (3) concise and readable - with only one line of code.\nAssume we have a list of JSON objects with only two keys: payment method and total amount. Let's explore some examples of how these functions work.\n**Map:** Perform the same operation on all elements in the list (e.g. adding a suffix to the values of the payment method).\npython\n\n```\nupdated_txn_list = list(map(lambda x: {\n                      'paymentMthd': f\"{x['paymentMthd']}_2024\",\n                      \"totalAmt\": x[\"totalAmt\"]\n                   }, txn_list))\n\nprint(updated_txn_list)\n\n# Output\n# [{'paymentMthd': 'Cryptocurrency_2024', 'totalAmt': 3339.85},\n# {'paymentMthd': 'Cash on delivery_2024', 'totalAmt': 872.52},\n# ...]\n```\n\n**Filter** : Obtain a subset of elements that meet a certain condition(s) (e.g. only records with cryptocurrency as the payment method).\npython\n\n```\nupdated_txn_list = list(map(lambda x: x, filter(lambda y: y[\"paymentMthd\"] == \"Cryptocurrency\", txn_list)))\n\nprint(updated_txn_list)\n\n# Output\n# [{'paymentMthd': 'Cryptocurrency', 'totalAmt': 3339.85},\n# {'paymentMthd': 'Cryptocurrency', 'totalAmt': 576.15},\n# ...]\n```\n\n**Reduce** : Get a single-valued outcome (e.g. summing or multiplying all elements).\npython\n\n```\nfrom functools import reduce\n\ntotal_amt_crypto = reduce(lambda acc, x: acc + x[\"totalAmt\"], updated_txn_list, 0)\n\nprint(total_amt_crypto)\n\n# Output\n# 250353984.67000002\n```\n\nWe can leverage these functions during the transformation steps in data science projects. For example, use `map()` to scale or normalize the data, use `filter()` to remove outliers and irrelevant data points, and `reduce()` to generate summary statistics.\n### 4 Data pipeline testing - Pytest\nData pipelines often involve data ingestion, data cleansing, and Extract-Transform-Load (ETL) operations. The scope of potential errors can be broad and easily overlooked, especially as the model flow and result are hard for users to interpret. This leads to a heavier reliance on testing efforts by the development team.\n> It is common to conduct unit testing to ascertain each component of the machine learning system performs as expected.\nOne of the most popular Python testing frameworks is `[Pytest](https://docs.pytest.org/en/stable/contents.html)`. Imagine we want to ensure the high-quality of transformed data that both technical teams and decision-makers can trust. We can test for the function that we have gone through about categorizing transaction prices. To achieve this, we need to prepare two Python files:\n  * **feature_engineering.py** : The file containing the previously built function\n\n\npython\n\n```\n# Categorize the total amount of each transaction\ndef add_features(sample_cases):\n  for txn in sample_cases:\n    price = txn['totalAmt']\n  if 0 <= price <= 1500:\n    txn['totalAmtCat'] = 'Low'\n  elif 1500 < price <= 3500:\n    txn['totalAmtCat'] = 'Moderate'\n  elif 3500 < price:\n    txn['totalAmtCat'] = 'High'\n\nreturn sample_cases\n```\n\n  * **test_feature_engineering.py** : The file with the \"test_\" prefix, which Pytest will recognize for testing purposes only.\n\n\npython\n\n```\nfrom feature_engineering import add_features\n\ndef test_add_features():\n  sample_cases = [{\n      'orderID': 1,\n      'customerID': 36536,\n      'productID': [2209, 2262, 4912, 3162, 5734],\n      'paymentMthd': 'Cryptocurrency',\n      'totalAmt': 576.15,\n      'invoiceTime': '2024–06–10T23:53:25.329928'\n    }]\n\n  # Call the function with the sample cases\n  sample_cases = add_features(sample_cases)\n\n  # Check the assertations\n  for txn in sample_cases: \n    assert 'totalAmtCat' in list(txn.keys())\n    assert len(txn) == 7\n    assert len(txn['totalAmtCat']) != 0\n```\n\nThe assert statements above ensure that the new 'totalAmtCat' data field is added with a non-blank value, and the original data fields are not affected. By executing the command `Pytest`, we can know that our test has passed!\n![Pytest result - Test passed \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/06/1HdAcJRXNoMUO7D4une7Sww-2.png)\nPytest result - Test passed (Image by author)\nFor a more advanced case, let's say we have three functions with the following sequences: `load_data`, `clean_data`, and `add_features`. How should we design the test file to validate the output of these functions one by one?\npython\n\n```\nimport pytest\nimport json\nfrom feature_engineering import load_data, clean_data, add_features\n\n# Set up a temporary JSONL file\n@pytest.fixture\ndef jsonl_file(tmp_path):\n  sample_cases = [{'orderID': 10000,\n    'customerID': 48316,\n    'productID': [5620],\n    'paymentMthd': 'Cash on delivery',\n    'totalAmt': 9301.2,\n    'invoiceTime': '2024-06-10T23:30:29.608443',\n    'price': -1\n  }]\n\n  file_path = tmp_path + \"/test_transactions.jsonl\"\n\n  with open(file_path, 'w') as f:\n    for txn in sample_cases:\n        f.write(json.dumps(txn) + \"n\")\n\n  return file_path\n\n# Test function to validate the `load_data` function\ndef test_load_data(jsonl_file):\n  data = load_data(jsonl_file)\n  # assert statements here\n\n# Test function to validate the `clean_data` function\ndef test_clean_data(jsonl_file):\n  data = load_data(jsonl_file)\n  data = clean_data(data)\n  # assert statements here\n\n# Test function to validate the `add_features` function\ndef test_add_features(jsonl_file):\n  data = load_data(jsonl_file)\n  data = clean_data(data)\n  data = add_features(data)\n  # assert statements here\n```\n\nWe should define a fixed baseline for initialization, such as a JSON Lines file with sample test cases. Here we use `@pytest.fixture`decorator, which works similarly to the `time_decorator`we discussed earlier in the Python decorator section. This decorator helps prevent repeatedly initializing the sample files. For the remaining codes, we involve several test functions to run the pipeline functions and use assert statements to detect logical errors.\n* * *\n### Wrapping it up\nWe came across several critical aspects of data engineering projects, and explored how to simplify and streamline the Python code for efficiency and readability:\n  * Data ingestion, by using `yield` to process large datasets with efficient memory usage.\n  * Data validation, by leveraging `Pydantic` to validate data fields based on schema and customized value patterns.\n  * Data processing, by applying Python decorator and built-in libraries to enable additional functionalities without repeated codes.\n  * Pipeline testing, by using `Pytest` to ensure high-quality function outputs throughout the workflow.\n\n\n* * *\n### Before you go\nIf you enjoy this reading, I invite you to **** follow my [Medium page](https://medium.com/@johnleungTJ) and [LinkedIn page](https://www.linkedin.com/in/john-leung-639800115/). By doing so, you can stay updated with exciting content related to data science side projects, Machine Learning Operations (MLOps) demonstrations, and project management methodologies.\n> [**Performing Customer Analytics with LangChain and LLMs**](https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5)\n> [**Feature Engineering for Time-Series Using PySpark on Databricks**](https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657188043_vu8s9b.jpeg)\nWritten By\n## [John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[See all from John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[Big Data](https://towardsdatascience.com/tag/big-data/)[Data Engineering](https://towardsdatascience.com/tag/data-engineering/)[Programming](https://towardsdatascience.com/tag/programming/)[Python](https://towardsdatascience.com/tag/python/)[Tips And Tricks](https://towardsdatascience.com/tag/tips-and-tricks/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&title=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&title=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fsimplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a%2F&text=Simplifying%20the%20Python%20Code%20for%20Data%20Engineering%20Projects)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/0s8NQ7Oi66NYtCW4F-scaled.jpg)](https://towardsdatascience.com/how-to-read-and-write-data-from-to-the-same-quip-spreadsheet-using-quip-apis-in-python-48f4db96bf72/)\n## [How to Read and Write Data from/to the Quip Spreadsheet using Quip Python APIs](https://towardsdatascience.com/how-to-read-and-write-data-from-to-the-same-quip-spreadsheet-using-quip-apis-in-python-48f4db96bf72/)\n[](https://towardsdatascience.com/simplifying-the-python-code-for-data-engineering-projects-95f0c41dc58a/)\nEnable end-users to provide their inputs that can then be used as overrides/additional context in the final analytical solution\n[Isha Garg](https://towardsdatascience.com/author/ishagarg2010/)\nNovember 17, 20237 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1Xea2rPaHXliOOIAl2_FJOg-scaled.jpeg)](https://towardsdatascience.com/behind-the-scenes-delta-lake-clones-d3578cff76a9/)\n## [Behind the scenes: Delta Lake Clones](https://towardsdatascience.com/behind-the-scenes-delta-lake-clones-d3578cff76a9/)\n[Programming](https://towardsdatascience.com/category/programming/)\nHow to clone your delta lake tables easily using Spark.\n[Prashanth Xavier](https://towardsdatascience.com/author/xavier211192/)\nMarch 14, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/0fTROh1eYgYFvdk6Y-scaled.jpg)](https://towardsdatascience.com/python-pandas-reading-a-csv-7865a11939fd/)\n## [Python Pandas Reading a CSV](https://towardsdatascience.com/python-pandas-reading-a-csv-7865a11939fd/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLearn how to read a CSV file and create a Pandas DataFrame\n[Dean McGrath](https://towardsdatascience.com/author/deanmcgrath/)\nFebruary 2, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/06/1yrkZTQ2FTXmS4hynR2Snrw-scaled.jpeg)](https://towardsdatascience.com/a-practical-guide-on-missing-values-with-pandas-8fb3e0b46c24/)\n## [A Practical Guide on Missing Values with Pandas](https://towardsdatascience.com/a-practical-guide-on-missing-values-with-pandas-8fb3e0b46c24/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA comprehensive guide to handle missing\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJune 13, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/1ZZ2xQ8qo64nGyj05Wl6cCg-scaled.jpeg)](https://towardsdatascience.com/practical-guide-for-virtual-environments-in-python-b59bd5fe8f1/)\n## [Practical Guide for Virtual Environments in Python](https://towardsdatascience.com/practical-guide-for-virtual-environments-in-python-b59bd5fe8f1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUsing virtualenv and pipenv tools\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJanuary 3, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/0TGqGovL9LpPCCXql-scaled.jpg)](https://towardsdatascience.com/a-gentle-introduction-to-self-training-and-semi-supervised-learning-ceee73178b38/)\n## [A Gentle Introduction to Self-Training and Semi-Supervised Learning](https://towardsdatascience.com/a-gentle-introduction-to-self-training-and-semi-supervised-learning-ceee73178b38/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCoding an example of self-training in Python to utilize unlabeled data for classification\n[Doug Steen](https://towardsdatascience.com/author/douglaspsteen/)\nAugust 30, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/1KL19CtrG03XqQ-bUvNXh0g-scaled.jpeg)](https://towardsdatascience.com/hashicorp-vault-airflow-cfdddab31ea/)\n## [How To Setup HashiCorp Vault with Airflow](https://towardsdatascience.com/hashicorp-vault-airflow-cfdddab31ea/)\n[Programming](https://towardsdatascience.com/category/programming/)\nIntegrating HashiCorp Vault with Apache Airflow\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJune 3, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/07/0pIevSQeMjAsnka6Y-scaled.jpg)](https://towardsdatascience.com/surviving-a-coding-bootcamp-2963915e2285/)\n## [Surviving a Coding Bootcamp](https://towardsdatascience.com/surviving-a-coding-bootcamp-2963915e2285/)\n[Programming](https://towardsdatascience.com/category/programming/)\nTips, Tricks, and Advice from a Coding Bootcamp Survivor\n[Jesse Neumann](https://towardsdatascience.com/author/jesse989/)\nJuly 22, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/07/1tSHEhImXzo4P87ZtVhADXw.jpeg)](https://towardsdatascience.com/apache-hadoop-a-review-on-security-issues-and-solutions-for-hdfs-5ba06861b7cd/)\n## [Apache Hadoop: A Review on Security Issues and Solutions for HDFS](https://towardsdatascience.com/apache-hadoop-a-review-on-security-issues-and-solutions-for-hdfs-5ba06861b7cd/)\n[Security](https://towardsdatascience.com/category/technology/security/)\nBig Data Solution A deep dive into the security issues that occur in HDFS structure,...\n[KahEm Chu](https://towardsdatascience.com/author/kahemchu/)\nDecember 4, 202015 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/1e719a54c65f/pages/",
  "body_markdown_path": "attachments/1e719a54c65f/pages/archived-body.md",
  "local_html": "attachments/1e719a54c65f/pages/archived-body.html",
  "body_source": "prior_capture"
}