{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "John Leung",
  "title_listed": "Feature Engineering for Time-Series Using PySpark on Databricks",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287/",
  "publish_date": "2024-05-15",
  "corpus_stage": "",
  "notes": "",
  "id": "8888feac2415",
  "collected_at": "2026-10-02T04:28:31",
  "title": "Feature Engineering for Time-Series Using PySpark on Databricks | 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[Data Science](https://towardsdatascience.com/category/data-science/)\n# Feature Engineering for Time-Series Using PySpark on Databricks\nDiscover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation codes\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nMay 15, 20249 min read\n### Discover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation code\nWith the increasing demand for high-speed querying and analysis on large datasets, [Apache Spark](https://spark.apache.org/) has stood out as one of the most popular analytical engines in recent years. It is powerful in distributed data processing due to its [master-worker architecture](https://towardsdatascience.com/a-beginners-guide-to-apache-spark-ff301cb4cd92). This includes a driver program that coordinates with the cluster manager (master) and controls the execution of distributing smaller tasks to worker nodes. Besides, designed as an in-memory data processing engine, Spark primarily uses RAM to store and manipulate data, rather than relying on disk storage. These coordinately facilitate faster execution of overall tasks.\n![Photo by Dawid Zawiła on Unsplash](../images/000.jpg)\nPhoto by [Dawid Zawiła](https://unsplash.com/@davealmine?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\n### Apache Spark: From low-level to high-level\nAt the lower level, its architecture is designed based on two main abstractions:\n  * Resilient Distributed Dataset ([RDD](https://spark.apache.org/docs/latest/rdd-programming-guide.html)) - A low-level data abstraction in which each dataset can be divided into logical portions and executed on cluster worker nodes, thus aiding in parallel programming.\n  * Directed Acyclic Graph ([DAG](https://sparkbyexamples.com/spark/what-is-dag-in-spark/)) - The representation that facilitates optimizing and scheduling the dependencies and sequences of tasks.\n\n\nAt the higher level, we can leverage a rich set of high-level tools using languages Scala, Python, or R. Examples of tools include [Spark SQL](https://spark.apache.org/sql/) for SQL and DataFrames, [Pandas API](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) on Spark for Pandas workloads, and [Structured Streaming](https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html) for stream processing.\nHowever, before enjoying these functionalities, we may need much effort to self-manage a Spark cluster with the setup of infrastructure and a bunch of complex tools, which could cause a headache.\n### PySpark on Databricks\nTo address these challenges, [PySpark](https://spark.apache.org/docs/latest/api/python/index.html) on [Databricks](https://docs.databricks.com/en/introduction/index.html) is recently one of the high-level solutions in the industry. PySpark is the Python API for Spark, while Databricks is a full software platform built on top of Spark. It includes notebooks, infrastructure orchestration (auto-provisioning and scaling), process orchestration (job submission and scheduling), managed clusters, and even source control.\n* * *\nUsing PySpark APIs in Databricks, we will demonstrate and perform a feature engineering project on time series data. In this hands-on journey, we will simulate how Pandas library generally behaves for data processing, with the extra benefits of scalability and parallelism.\n_Note: If you want to know further how to dynamically orchestrate this Databricks notebook written in PySpark APIs in Azure, you can click_[ _here_](https://medium.com/towards-data-science/orchestrating-a-dynamic-time-series-pipeline-with-azure-data-factory-and-databricks-810819608231) _._\n![Photo by Alexandru Boicu on Unsplash](../images/001.jpg)\nPhoto by [Alexandru Boicu](https://unsplash.com/@boiq?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nConsider a scenario in which you have the electric power consumption data for your household on hand, sampled at a one-minute rate from December 2006 to November 2010. Our objective is to ingest and manipulate data, extract features, and generate visualizations.\nThe [dataset](https://www.kaggle.com/datasets/uciml/electric-power-consumption-data-set/data) [with license as [Database: Open Database, Contents: Database Contents](https://opendatacommons.org/licenses/dbcl/1-0/)], obtained from Kaggle, includes various fields such as date, time, global power (active and reactive), voltage, global intensity, and submetering (1, 2 and 3). We can begin our analysis now.\n### The initial setup\nTo begin, we need to create a user account for [Databricks Community Edition](https://www.databricks.com/product/faq/community-edition), which gives a suitable Databricks environment for our proof-of-concept purpose. Afterward, we can upload the input data file to the FileStore, a dedicated Databricks path. By clicking \"Create Table in Notebook\", you are provided with the code template to initiate data ingestion.\n![Initial setup \\(1/2\\) - Create a user account \\(Image by author\\)](../images/002.png)\nInitial setup (1/2) - Create a user account (Image by author)\n![Initial setup \\(2/2\\) - Create a new table \\(Image by author\\)](../images/003.png)\nInitial setup (2/2) - Create a new table (Image by author)\n### Create a feature engineering project\n**#1 Ingest data**\n  * Static data\n\n\nWe use the method `spark.read()` to read our data source and return a DataFrame, a relational table. It supports various data sources such as CSV, JSON, Parquet, and more. In this case, we read the power consumption data in CSV format with a defined schema, where the first row serves as the header, and \";\" is as the delimiter.\npython\n\n```\n# File location and type\nfile_location = \"/FileStore/tables/household_power_consumption.csv\"\nfile_type = \"csv\"\n\n# CSV options\nschema = \"Date STRING, Time STRING, Global_active_power DOUBLE, Global_reactive_power DOUBLE, Voltage DOUBLE, Global_intensity DOUBLE, Sub_metering_1 DOUBLE, Sub_metering_2 DOUBLE, Sub_metering_3 DOUBLE\"\nfirst_row_as_header = \"true\"\ndelimiter = \";\"\n\n# Read CSV files\norg_df = spark.read.format(file_type) \n.schema(schema) \n.option(\"header\", first_row_as_header) \n.option(\"delimiter\", delimiter) \n.load(file_location)\n\ndisplay(org_df)\n```\n\nThe output of the DataFrame with the first several rows:\n![Output of the DataFrame \\(Image by author\\)](../images/004.png)\nOutput of the DataFrame (Image by author)\n  * Streaming data\n\n\nIn scenarios where data is continuously generated, we use stream processing techniques to read it incrementally. To demonstrate Spark's behavior, I partitioned the original dataset into 10 subsets and stored them at the path \"/FileStore/tables/stream/\" beforehand. We then use another method `spark.readStream()`for streaming data.\npython\n\n```\nsourceStream=spark.readStream.format(\"csv\") \n.option(\"header\",True) \n.schema(schema) \n.option(\"mode\",\"dropMalformed\") \n.option(\"maxFilesPerTrigger\",1) \n.option(\"ignoreLeadingWhiteSpace\",True) \n.load(\"dbfs:/FileStore/tables/stream\") \n```\n\nIt is worth mentioning that the `mode` setting as \"dropMalformed\" means that we discard the corrupted records, no matter whether the corruption is due to structural inconsistencies or other factors that make them unusable. Also, we choose to process only one file per trigger event.\nBy starting to receive data and checking the record count every ten seconds, we can observe the continuous arrival of streaming data.\npython\n\n```\nimport time\n\n# Stream the content of the DataFrame\nquery = sourceStream.writeStream \n.queryName(\"count\") \n.format(\"memory\") \n.outputMode(\"append\") \n.start()\n\n# Display the count of rows\nfor _ in range(10):\n  spark.sql(\"SELECT COUNT(*) AS no_of_rows FROM count\").show()\n  time.sleep(10)\n```\n\n**#2 Manipulate and explore data**\n  * Data transformation\n\n\nSince the number of rows with missing values is relatively negligible, we choose to drop them. Besides, we extract time-related features so that patterns can potentially be observed in higher dimensions later.\npython\n\n```\nfrom pyspark.sql.functions import col, concat_ws, to_date\n\n# Drop rows with missing values\ndf = org_df.na.drop()\n\n# Convert columns \"Date\" and \"Time\" into new column \"DateTime\"\ndf = df.withColumn(\"Date\", to_date(col(\"Date\"),\"d/M/y\"))\ndf = df.withColumn(\"Date\", df[\"Date\"].cast(\"date\"))\ndf = df.select(concat_ws(\" \", to_date(col(\"Date\"),\"d/M/y\"), col(\"Time\")).alias(\"DateTime\"), \"*\")\ndf = df.withColumn(\"DateTime\", df[\"DateTime\"].cast(\"timestamp\"))\n\n# Add time-related features\ndf = df.withColumn(\"year\", year(\"DateTime\"))\ndf = df.withColumn(\"month\", month(\"DateTime\"))\ndf = df.withColumn(\"week_num\", weekofyear(\"DateTime\"))\ndf = df.withColumn(\"hour\", hour(\"DateTime\"))\n```\n\n  * Data exploration\n\n\nWe can explore data with various basic [PySpark methods](https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.DataFrame.html).\n(1) Select\nThe \"'select\" method allows us to create a subset of the data frame column-wise. In this example, we select columns in descending order of global active power.\npython\n\n```\ndf.select(\"DateTime\", \"Global_active_power\", \"Global_intensity\").sort(\"Global_active_power\", ascending=False).show(5)\n```\n\n![Output of &quot;select&quot; method \\(Image by author\\)](../images/005.png)\nOutput of \"select\" method (Image by author)\n(2) Filter\nThis filters data points based on column values. In this example, we filter by two columns: \"year\" and \"Global_intensity\".\npython\n\n```\ndf.filter(\n    (col(\"year\") == 2009) &amp;\n    (col(\"Global_intensity\") > 40)\n).count()\n\n# Output: 10\n```\n\n(3) groupby\nWe can also perform some aggregations. In our dataset, we calculate the average of global active power and sub-meterings for different months.\npython\n\n```\ndf.groupby(\"month\").agg(\n     round(mean(\"Global_active_power\"), 2).alias(\"Avg_global_active_power\"),\n     round(mean(\"Sub_metering_1\"), 2).alias(\"Avg_sub_metering_1\"),\n     round(mean(\"Sub_metering_2\"), 2).alias(\"Avg_sub_metering_2\"),\n     round(mean(\"Sub_metering_3\"), 2).alias(\"Avg_sub_metering_3\"),\n).sort([\"month\"]).show(5)\n```\n\n![Output of &quot;groupby&quot; method \\(Image by author\\)](../images/006.png)\nOutput of \"groupby\" method (Image by author)\n**#3 Extract features using Window functions**\nIn addition to the above basic PySpark methods and functions, we can leverage [Window functions](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.Window.html) to generate additional features to capture temporal dependencies and relationships in time series data. Assuming we have a transformed dataset (\"df2\") where the total global active power is aggregated by day from one-minute rate samples. Let's explore how we can obtain these features.\n(1) Lag features\nThese represent the metrics' values from previous days, which aids our models in learning from historical data and identifying trends.\npython\n\n```\nfrom pyspark.sql.window import Window\nfrom pyspark.sql.functions import lag, round\n\n# Create a Window specification based on the 'Date' column\nwindowSpec = Window.orderBy(\"Date\")\n\n# Calculate the lagged value of 'Total_global_active_power'\ndf2 = df2.withColumn(\"power_lag1\", round(lag(col(\"Total_global_active_power\"), 1).over(windowSpec), 2))\n\ndisplay(df2)\n```\n\n![Output - Lag features \\(Image by author\\)](../images/007.png)\nOutput - Lag features (Image by author)\n(2) Delta features\nThis is to take a subsequent step to capture short-term changes or variations over time by calculating the difference between original data fields and the lag features.\npython\n\n```\n# Calculate the difference between columns\ndf2 = df2.withColumn(\"power_lag1_delta\", round(col(\"power_lag1\") - col(\"Total_global_active_power\"), 2))\n\ndisplay(df2)\n```\n\n![Output - Delta features \\(Image by author\\)](../images/008.png)\nOutput - Delta features (Image by author)\n(3) Window average features\nThese features calculate the average value of our target data fields within a sliding window, enabling us to capture the smoothed patterns and relatively long-term trends. Here I pick the window sizes as 14 (2 weeks) and 30 (roughly 1 month).\npython\n\n```\n# Add window average fields to the DataFrame for the specified window sizes\ndef add_window_avg_features(df, window_sizes):\n    for window_size in window_sizes:\n        window_col_name = f\"avg_power_l{window_size}\"\n        windowSpec = Window.orderBy(\"Date\").rowsBetween(-window_size, 0)\n        df = df.withColumn(window_col_name, round(avg(col(\"Total_global_active_power\")).over(windowSpec), 2))\n    return df\n\nwindow_sizes = [14, 30]\ndf2 = add_window_avg_features(df2, window_sizes)\n\ndf2.select(\"Date\", \"Total_global_active_power\", \"avg_power_l14\", \"avg_power_l30\").sort(\"Date\", ascending=False).show(5)\n```\n\n![Output - Window average features \\(Image by author\\)](../images/009.png)\nOutput - Window average features (Image by author)\n(4) Exponentially weighted moving average (EWMA) features\nEWMA features are the rectified version of window average features by assigning more weight and emphasis to recent data, and less to past data. A higher value of weight (alpha) means that the EWMA features track more closely to the original time series. Here I pick two separate weights: 0.2 and 0.8.\npython\n\n```\nimport pyspark.pandas as ps\n\n#  Add EWMA features to the DataFrame for the specified alpha values\ndef add_ewma_features(df, alphas):\n    for alpha in alphas:\n        ewma_col_name = f\"ewma_power_w{str(alpha).replace('.', '')}\"\n        windowSpec = Window.orderBy(\"Date\")\n        df[ewma_col_name] = df.Total_global_active_power.ewm(alpha=alpha).mean().round(2)\n    return df\n\nalphas = [0.2, 0.8]\n# Convert into a pandas-on-Spark DataFrame, to use EWM function\ndf2_pd = df2.pandas_api()\ndf2_pd = add_ewma_features(df2_pd, alphas)\n# Convert back to a Spark DataFrame\ndf2 = df2_pd.to_spark()\n\ndf2.select(\"Date\", \"Total_global_active_power\", \"ewma_power_w02\", \"ewma_power_w08\").sort(\"Date\", ascending=False).show(5)\n```\n\n![Output - EWMA features \\(Image by author\\)](../images/010.png)\nOutput - EWMA features (Image by author)\n**#4 Generate visualizations on Notebook**\nAfter extracting time-related data and features using various PySpark functions and methods, we can use the built-in support from Databricks to create visualizations efficiently. This works by dragging and dropping data fields and configuring visual settings in the visualization editor. Some examples are shown below.\n  * Scatter plot: Relationship between global active power and global intensity\n\n\n_Interpretation: There is a highly positive correlation between the two fields._\n![Scatter plot, using a visualization editor \\(Image by author\\)](../images/011.png)\nScatter plot, using a visualization editor (Image by author)\n  * Box plot: The distribution of global active power across hours\n\n\n_Interpretation: There are relatively large variations of global active power from 7:00 to 21:00._\n![Box plot \\(Image by author\\)](../images/012.png)\nBox plot (Image by author)\n  * Line chart: The changes in total global active power, EWMA with alpha 0.2, and EWMA with alpha 0.8 from Jan 2008 to Mar 2008\n\n\n_Interpretation: EWMA with alpha 0.8 sticks more closely to the original time series than EWMA with alpha 0.2._\n![Line chart \\(Image by author\\)](../images/body-9568a4bae424edc192d2.png)\nLine chart (Image by author)\nBesides, we can generate the default data profiles to display summary statistics such as count, % of missing values, and data distributions. This ensures data quality throughout the entire feature engineering process. These above visualizations can alternatively be created by the query output using Databricks SQL.\n### Wrapping it up\nIn our hands-on exploration, we used PySpark for feature engineering of time-series data using the Databricks platform:\n  * Ingesting static and streaming data, by using the `spark.read()` and `spark.readStream()` methods respectively.\n  * Manipulating and exploring data, by using a range of basic PySpark functions available in `pyspark.sql.functions`, and DataFrame methods.\n  * Extract trend-related features, by calculating the relationship within groups of data using `pyspark.sql.Window`.\n  * Visualization, by using the built-in features of Databricks Notebook.\n\n\nWhen dealing with a massive dataset, PySpark is often preferred over Pandas due to its scalability and performance capabilities. PySpark's support for lazy evaluation also means that computations are only performed when necessary, which reduces the overhead. However, Scala can sometimes be a better option, because we can closely catch up with the latest features as Spark itself is written in Scala. And more likely that systems which are less error-prone can be designed with the use of immutable objects. Different languages or libraries have their edges. Ultimately, the choice depends on the enterprise requirements, developers' learning curves, and integration with other systems.\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, and Machine Learning Operations (MLOps) demonstrations methodologies.\n> [**Performing Customer Analytics with LangChain and LLMs**](https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5)\n> [**Managing the Technical Debts of Machine Learning Systems**](https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d)\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 Science](https://towardsdatascience.com/tag/data-science/)[Databricks](https://towardsdatascience.com/tag/databricks/)[Python](https://towardsdatascience.com/tag/python/)[Spark](https://towardsdatascience.com/tag/spark/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&title=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&title=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&text=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\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/013.png)](https://towardsdatascience.com/your-pathway-to-success-how-you-can-land-a-machine-learning-and-data-science-internship-c14825b58420/)\n## [Your Pathway to Success: How You Can Land a Machine Learning and Data Science Internship](https://towardsdatascience.com/your-pathway-to-success-how-you-can-land-a-machine-learning-and-data-science-internship-c14825b58420/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAdvice and tips from a data scientist who landed two internships in a year\n[Sara Nobrega](https://towardsdatascience.com/author/saranobregafn/)\nSeptember 4, 202415 min read\n  * [![](../images/014.jpg)](https://towardsdatascience.com/how-python-enumerations-make-data-configuration-elegant-a7d8356657bd/)\n## [How Python Enumerations Make Data Configuration Elegant](https://towardsdatascience.com/how-python-enumerations-make-data-configuration-elegant-a7d8356657bd/)\n[Programming](https://towardsdatascience.com/category/programming/)\nAn introduction to using Enums in Python for ML projects\n[Eirik Berge](https://towardsdatascience.com/author/ebbeberge/)\nMay 28, 20238 min read\n  * [![](../images/015.png)](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-how-to-track-data-quality-and-integrity-391435c8a299/)\n## [Monitoring Machine Learning Models in Production: How to Track Data Quality and Integrity?](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-how-to-track-data-quality-and-integrity-391435c8a299/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAs the saying goes: garbage in is garbage out. Input data quality is the most crucial component of a machine learning system. Whether or...\n[Emeli Dral](https://towardsdatascience.com/author/emeli.dral/)\nJanuary 19, 202113 min read\n  * [![](../images/016.jpeg)](https://towardsdatascience.com/10-free-tools-to-instantly-get-started-with-data-visualisation-d7fadb5f6dce/)\n## [10 Free tools to get started with Data Visualisation-Easily & Instantly.](https://towardsdatascience.com/10-free-tools-to-instantly-get-started-with-data-visualisation-d7fadb5f6dce/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nJump right into the Data Visualisation process with these easy and intuitive tools.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nMarch 12, 20199 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/how-to-cross-validate-your-panel-data-in-python-9ad981ddd043/)\n## [How to cross validate your panel data in Python](https://towardsdatascience.com/how-to-cross-validate-your-panel-data-in-python-9ad981ddd043/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn introduction to panel data cross validation using PanelSplit\n[Eric Frey](https://towardsdatascience.com/author/eric.frey/)\nMarch 8, 20245 min read\n  * [![](../images/018.jpg)](https://towardsdatascience.com/data-science-workflows-with-the-targets-package-in-r-end-to-end-example-with-code-1e31318074c4/)\n## [Data science workflows with the Targets package in R : End-to-end example with code](https://towardsdatascience.com/data-science-workflows-with-the-targets-package-in-r-end-to-end-example-with-code-1e31318074c4/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nStructured and reproducible approach for analysis\n[Prateek Bhatnagar](https://towardsdatascience.com/author/prateek-bhatnagar89/)\nAugust 19, 20213 min read\n  * [![](../images/019.png)](https://towardsdatascience.com/why-you-should-start-using-npy-file-more-often-df2a13cc0161/)\n## [Why you should start using .npy file more often...](https://towardsdatascience.com/why-you-should-start-using-npy-file-more-often-df2a13cc0161/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nNative NumPy objects in Python provides speed advantage over regular objects. It works for as simple a task as reading data from file.\n[Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\nMarch 20, 20186 min read\n  * [![](../images/020.jpg)](https://towardsdatascience.com/recreating-a-538-elections-plot-making-custom-matplotlib-visualizations-b6ede7a406b4/)\n## [Recreating a 538 election's plot: making custom matplotlib visualizations](https://towardsdatascience.com/recreating-a-538-elections-plot-making-custom-matplotlib-visualizations-b6ede7a406b4/)\n[Programming](https://towardsdatascience.com/category/programming/)\nI have recently been interested in making highly customizable visualizations. Here is one example of trying to recreate 538's election...\n[Dea Bardhoshi](https://towardsdatascience.com/author/deabardhoshi/)\nFebruary 22, 20222 min read\n  * [![](../images/021.jpeg)](https://towardsdatascience.com/the-data-scientist-who-rules-the-data-science-for-good-competitions-on-kaggle-ab436595a29f/)\n## [The Data Scientist who rules the 'Data Science for Good' competitions on Kaggle.](https://towardsdatascience.com/the-data-scientist-who-rules-the-data-science-for-good-competitions-on-kaggle-ab436595a29f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn conversation with Shivam Bansal: A Data Scientist, a Kaggle Kernel's Grandmaster, and three times winner of Kaggle's Data Science for...\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nOctober 18, 20197 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": "Feature Engineering for Time-Series Using PySpark on Databricks | Towards Data Science",
    "description": "Discover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation codes",
    "keywords": null,
    "author": "John Leung",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Feature Engineering for Time-Series Using PySpark on Databricks",
    "og:description": "Discover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation codes",
    "og:url": "https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0Snni4h4UW_ZcQYmh-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1715",
    "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": "9 min read",
    "article:published_time": "2024-05-15T06:10:27.000Z",
    "article:modified_time": "2024-05-15T06:10:27.000Z",
    "article:author": "https://towardsdatascience.com/author/johnleungtj/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_000.txt",
      "chars": 560
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_001.txt",
      "chars": 233
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_002.txt",
      "chars": 286
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_003.txt",
      "chars": 669
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_004.txt",
      "chars": 118
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_005.txt",
      "chars": 102
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_006.txt",
      "chars": 329
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_007.txt",
      "chars": 358
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_008.txt",
      "chars": 162
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_009.txt",
      "chars": 606
    },
    {
      "language": "txt",
      "file": "attachments/8888feac2415/code/block_010.txt",
      "chars": 712
    }
  ],
  "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-20T17:36:14Z"
    },
    {
      "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-20T17:36:14Z"
    },
    {
      "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-20T17:36:14Z"
    },
    {
      "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-20T17:36:14Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "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/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/johnleungtj/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/a-beginners-guide-to-apache-spark-ff301cb4cd92"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/big-data/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/databricks/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/spark/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/your-pathway-to-success-how-you-can-land-a-machine-learning-and-data-science-internship-c14825b58420/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/saranobregafn/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-python-enumerations-make-data-configuration-elegant-a7d8356657bd/"
    },
    {
      "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://spark.apache.org/"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@davealmine"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/docs/latest/rdd-programming-guide.html"
    },
    {
      "type": "external",
      "href": "https://sparkbyexamples.com/spark/what-is-dag-in-spark/"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/sql/"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/docs/latest/api/python/index.html"
    },
    {
      "type": "external",
      "href": "https://docs.databricks.com/en/introduction/index.html"
    },
    {
      "type": "external",
      "href": "https://medium.com/towards-data-science/orchestrating-a-dynamic-time-series-pipeline-with-azure-data-factory-and-databricks-810819608231"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@boiq"
    },
    {
      "type": "external",
      "href": "https://www.kaggle.com/datasets/uciml/electric-power-consumption-data-set/data"
    },
    {
      "type": "external",
      "href": "https://opendatacommons.org/licenses/dbcl/1-0/"
    },
    {
      "type": "external",
      "href": "https://www.databricks.com/product/faq/community-edition"
    },
    {
      "type": "external",
      "href": "https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.DataFrame.html"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:23:07Z",
  "source_url": "https://towardsdatascience.com/feature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "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[Data Science](https://towardsdatascience.com/category/data-science/)\n# Feature Engineering for Time-Series Using PySpark on Databricks\nDiscover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation codes\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nMay 15, 20249 min read\n### Discover the potentials of PySpark for time-series data: Ingest, extract, and visualize data, accompanied by practical implementation code\nWith the increasing demand for high-speed querying and analysis on large datasets, [Apache Spark](https://spark.apache.org/) has stood out as one of the most popular analytical engines in recent years. It is powerful in distributed data processing due to its [master-worker architecture](https://towardsdatascience.com/a-beginners-guide-to-apache-spark-ff301cb4cd92). This includes a driver program that coordinates with the cluster manager (master) and controls the execution of distributing smaller tasks to worker nodes. Besides, designed as an in-memory data processing engine, Spark primarily uses RAM to store and manipulate data, rather than relying on disk storage. These coordinately facilitate faster execution of overall tasks.\n![Photo by Dawid Zawiła on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0Snni4h4UW_ZcQYmh-scaled.jpg)\nPhoto by [Dawid Zawiła](https://unsplash.com/@davealmine?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\n### Apache Spark: From low-level to high-level\nAt the lower level, its architecture is designed based on two main abstractions:\n  * Resilient Distributed Dataset ([RDD](https://spark.apache.org/docs/latest/rdd-programming-guide.html)) - A low-level data abstraction in which each dataset can be divided into logical portions and executed on cluster worker nodes, thus aiding in parallel programming.\n  * Directed Acyclic Graph ([DAG](https://sparkbyexamples.com/spark/what-is-dag-in-spark/)) - The representation that facilitates optimizing and scheduling the dependencies and sequences of tasks.\n\n\nAt the higher level, we can leverage a rich set of high-level tools using languages Scala, Python, or R. Examples of tools include [Spark SQL](https://spark.apache.org/sql/) for SQL and DataFrames, [Pandas API](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) on Spark for Pandas workloads, and [Structured Streaming](https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html) for stream processing.\nHowever, before enjoying these functionalities, we may need much effort to self-manage a Spark cluster with the setup of infrastructure and a bunch of complex tools, which could cause a headache.\n### PySpark on Databricks\nTo address these challenges, [PySpark](https://spark.apache.org/docs/latest/api/python/index.html) on [Databricks](https://docs.databricks.com/en/introduction/index.html) is recently one of the high-level solutions in the industry. PySpark is the Python API for Spark, while Databricks is a full software platform built on top of Spark. It includes notebooks, infrastructure orchestration (auto-provisioning and scaling), process orchestration (job submission and scheduling), managed clusters, and even source control.\n* * *\nUsing PySpark APIs in Databricks, we will demonstrate and perform a feature engineering project on time series data. In this hands-on journey, we will simulate how Pandas library generally behaves for data processing, with the extra benefits of scalability and parallelism.\n_Note: If you want to know further how to dynamically orchestrate this Databricks notebook written in PySpark APIs in Azure, you can click_[ _here_](https://medium.com/towards-data-science/orchestrating-a-dynamic-time-series-pipeline-with-azure-data-factory-and-databricks-810819608231) _._\n![Photo by Alexandru Boicu on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/0jFGVo0U1jxlYynzr-1-scaled.jpg)\nPhoto by [Alexandru Boicu](https://unsplash.com/@boiq?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nConsider a scenario in which you have the electric power consumption data for your household on hand, sampled at a one-minute rate from December 2006 to November 2010. Our objective is to ingest and manipulate data, extract features, and generate visualizations.\nThe [dataset](https://www.kaggle.com/datasets/uciml/electric-power-consumption-data-set/data) [with license as [Database: Open Database, Contents: Database Contents](https://opendatacommons.org/licenses/dbcl/1-0/)], obtained from Kaggle, includes various fields such as date, time, global power (active and reactive), voltage, global intensity, and submetering (1, 2 and 3). We can begin our analysis now.\n### The initial setup\nTo begin, we need to create a user account for [Databricks Community Edition](https://www.databricks.com/product/faq/community-edition), which gives a suitable Databricks environment for our proof-of-concept purpose. Afterward, we can upload the input data file to the FileStore, a dedicated Databricks path. By clicking \"Create Table in Notebook\", you are provided with the code template to initiate data ingestion.\n![Initial setup \\(1/2\\) - Create a user account \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1aD-5_gyqJtuLxJ-FHkhryQ-1.png)\nInitial setup (1/2) - Create a user account (Image by author)\n![Initial setup \\(2/2\\) - Create a new table \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1WmkI7UfRBSWsrHX9gj_eqg-1.png)\nInitial setup (2/2) - Create a new table (Image by author)\n### Create a feature engineering project\n**#1 Ingest data**\n  * Static data\n\n\nWe use the method `spark.read()` to read our data source and return a DataFrame, a relational table. It supports various data sources such as CSV, JSON, Parquet, and more. In this case, we read the power consumption data in CSV format with a defined schema, where the first row serves as the header, and \";\" is as the delimiter.\npython\n\n```\n# File location and type\nfile_location = \"/FileStore/tables/household_power_consumption.csv\"\nfile_type = \"csv\"\n\n# CSV options\nschema = \"Date STRING, Time STRING, Global_active_power DOUBLE, Global_reactive_power DOUBLE, Voltage DOUBLE, Global_intensity DOUBLE, Sub_metering_1 DOUBLE, Sub_metering_2 DOUBLE, Sub_metering_3 DOUBLE\"\nfirst_row_as_header = \"true\"\ndelimiter = \";\"\n\n# Read CSV files\norg_df = spark.read.format(file_type) \n.schema(schema) \n.option(\"header\", first_row_as_header) \n.option(\"delimiter\", delimiter) \n.load(file_location)\n\ndisplay(org_df)\n```\n\nThe output of the DataFrame with the first several rows:\n![Output of the DataFrame \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/10auUJ0iUEbnOijWmJyW60w-1.png)\nOutput of the DataFrame (Image by author)\n  * Streaming data\n\n\nIn scenarios where data is continuously generated, we use stream processing techniques to read it incrementally. To demonstrate Spark's behavior, I partitioned the original dataset into 10 subsets and stored them at the path \"/FileStore/tables/stream/\" beforehand. We then use another method `spark.readStream()`for streaming data.\npython\n\n```\nsourceStream=spark.readStream.format(\"csv\") \n.option(\"header\",True) \n.schema(schema) \n.option(\"mode\",\"dropMalformed\") \n.option(\"maxFilesPerTrigger\",1) \n.option(\"ignoreLeadingWhiteSpace\",True) \n.load(\"dbfs:/FileStore/tables/stream\") \n```\n\nIt is worth mentioning that the `mode` setting as \"dropMalformed\" means that we discard the corrupted records, no matter whether the corruption is due to structural inconsistencies or other factors that make them unusable. Also, we choose to process only one file per trigger event.\nBy starting to receive data and checking the record count every ten seconds, we can observe the continuous arrival of streaming data.\npython\n\n```\nimport time\n\n# Stream the content of the DataFrame\nquery = sourceStream.writeStream \n.queryName(\"count\") \n.format(\"memory\") \n.outputMode(\"append\") \n.start()\n\n# Display the count of rows\nfor _ in range(10):\n  spark.sql(\"SELECT COUNT(*) AS no_of_rows FROM count\").show()\n  time.sleep(10)\n```\n\n**#2 Manipulate and explore data**\n  * Data transformation\n\n\nSince the number of rows with missing values is relatively negligible, we choose to drop them. Besides, we extract time-related features so that patterns can potentially be observed in higher dimensions later.\npython\n\n```\nfrom pyspark.sql.functions import col, concat_ws, to_date\n\n# Drop rows with missing values\ndf = org_df.na.drop()\n\n# Convert columns \"Date\" and \"Time\" into new column \"DateTime\"\ndf = df.withColumn(\"Date\", to_date(col(\"Date\"),\"d/M/y\"))\ndf = df.withColumn(\"Date\", df[\"Date\"].cast(\"date\"))\ndf = df.select(concat_ws(\" \", to_date(col(\"Date\"),\"d/M/y\"), col(\"Time\")).alias(\"DateTime\"), \"*\")\ndf = df.withColumn(\"DateTime\", df[\"DateTime\"].cast(\"timestamp\"))\n\n# Add time-related features\ndf = df.withColumn(\"year\", year(\"DateTime\"))\ndf = df.withColumn(\"month\", month(\"DateTime\"))\ndf = df.withColumn(\"week_num\", weekofyear(\"DateTime\"))\ndf = df.withColumn(\"hour\", hour(\"DateTime\"))\n```\n\n  * Data exploration\n\n\nWe can explore data with various basic [PySpark methods](https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.DataFrame.html).\n(1) Select\nThe \"'select\" method allows us to create a subset of the data frame column-wise. In this example, we select columns in descending order of global active power.\npython\n\n```\ndf.select(\"DateTime\", \"Global_active_power\", \"Global_intensity\").sort(\"Global_active_power\", ascending=False).show(5)\n```\n\n![Output of &quot;select&quot; method \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1nvT_fGjAWEH7i9SYjbBgAg-1.png)\nOutput of \"select\" method (Image by author)\n(2) Filter\nThis filters data points based on column values. In this example, we filter by two columns: \"year\" and \"Global_intensity\".\npython\n\n```\ndf.filter(\n    (col(\"year\") == 2009) &amp;\n    (col(\"Global_intensity\") > 40)\n).count()\n\n# Output: 10\n```\n\n(3) groupby\nWe can also perform some aggregations. In our dataset, we calculate the average of global active power and sub-meterings for different months.\npython\n\n```\ndf.groupby(\"month\").agg(\n     round(mean(\"Global_active_power\"), 2).alias(\"Avg_global_active_power\"),\n     round(mean(\"Sub_metering_1\"), 2).alias(\"Avg_sub_metering_1\"),\n     round(mean(\"Sub_metering_2\"), 2).alias(\"Avg_sub_metering_2\"),\n     round(mean(\"Sub_metering_3\"), 2).alias(\"Avg_sub_metering_3\"),\n).sort([\"month\"]).show(5)\n```\n\n![Output of &quot;groupby&quot; method \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1GV-zkSb77-esqtjNq0hKsw-1.png)\nOutput of \"groupby\" method (Image by author)\n**#3 Extract features using Window functions**\nIn addition to the above basic PySpark methods and functions, we can leverage [Window functions](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.Window.html) to generate additional features to capture temporal dependencies and relationships in time series data. Assuming we have a transformed dataset (\"df2\") where the total global active power is aggregated by day from one-minute rate samples. Let's explore how we can obtain these features.\n(1) Lag features\nThese represent the metrics' values from previous days, which aids our models in learning from historical data and identifying trends.\npython\n\n```\nfrom pyspark.sql.window import Window\nfrom pyspark.sql.functions import lag, round\n\n# Create a Window specification based on the 'Date' column\nwindowSpec = Window.orderBy(\"Date\")\n\n# Calculate the lagged value of 'Total_global_active_power'\ndf2 = df2.withColumn(\"power_lag1\", round(lag(col(\"Total_global_active_power\"), 1).over(windowSpec), 2))\n\ndisplay(df2)\n```\n\n![Output - Lag features \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/14Avt7uCS97MXC4j29liYRg-1.png)\nOutput - Lag features (Image by author)\n(2) Delta features\nThis is to take a subsequent step to capture short-term changes or variations over time by calculating the difference between original data fields and the lag features.\npython\n\n```\n# Calculate the difference between columns\ndf2 = df2.withColumn(\"power_lag1_delta\", round(col(\"power_lag1\") - col(\"Total_global_active_power\"), 2))\n\ndisplay(df2)\n```\n\n![Output - Delta features \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1e9jhhfVhsFpJlnHTbtiffQ-1.png)\nOutput - Delta features (Image by author)\n(3) Window average features\nThese features calculate the average value of our target data fields within a sliding window, enabling us to capture the smoothed patterns and relatively long-term trends. Here I pick the window sizes as 14 (2 weeks) and 30 (roughly 1 month).\npython\n\n```\n# Add window average fields to the DataFrame for the specified window sizes\ndef add_window_avg_features(df, window_sizes):\n    for window_size in window_sizes:\n        window_col_name = f\"avg_power_l{window_size}\"\n        windowSpec = Window.orderBy(\"Date\").rowsBetween(-window_size, 0)\n        df = df.withColumn(window_col_name, round(avg(col(\"Total_global_active_power\")).over(windowSpec), 2))\n    return df\n\nwindow_sizes = [14, 30]\ndf2 = add_window_avg_features(df2, window_sizes)\n\ndf2.select(\"Date\", \"Total_global_active_power\", \"avg_power_l14\", \"avg_power_l30\").sort(\"Date\", ascending=False).show(5)\n```\n\n![Output - Window average features \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1uarOPKDRUEbsW9npvi2xFQ-1.png)\nOutput - Window average features (Image by author)\n(4) Exponentially weighted moving average (EWMA) features\nEWMA features are the rectified version of window average features by assigning more weight and emphasis to recent data, and less to past data. A higher value of weight (alpha) means that the EWMA features track more closely to the original time series. Here I pick two separate weights: 0.2 and 0.8.\npython\n\n```\nimport pyspark.pandas as ps\n\n#  Add EWMA features to the DataFrame for the specified alpha values\ndef add_ewma_features(df, alphas):\n    for alpha in alphas:\n        ewma_col_name = f\"ewma_power_w{str(alpha).replace('.', '')}\"\n        windowSpec = Window.orderBy(\"Date\")\n        df[ewma_col_name] = df.Total_global_active_power.ewm(alpha=alpha).mean().round(2)\n    return df\n\nalphas = [0.2, 0.8]\n# Convert into a pandas-on-Spark DataFrame, to use EWM function\ndf2_pd = df2.pandas_api()\ndf2_pd = add_ewma_features(df2_pd, alphas)\n# Convert back to a Spark DataFrame\ndf2 = df2_pd.to_spark()\n\ndf2.select(\"Date\", \"Total_global_active_power\", \"ewma_power_w02\", \"ewma_power_w08\").sort(\"Date\", ascending=False).show(5)\n```\n\n![Output - EWMA features \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1DO7N1C4V8vnPqcAC21B7og-1.png)\nOutput - EWMA features (Image by author)\n**#4 Generate visualizations on Notebook**\nAfter extracting time-related data and features using various PySpark functions and methods, we can use the built-in support from Databricks to create visualizations efficiently. This works by dragging and dropping data fields and configuring visual settings in the visualization editor. Some examples are shown below.\n  * Scatter plot: Relationship between global active power and global intensity\n\n\n_Interpretation: There is a highly positive correlation between the two fields._\n![Scatter plot, using a visualization editor \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1Fim8xcbWtUWgeO-t3s7zkQ-1.png)\nScatter plot, using a visualization editor (Image by author)\n  * Box plot: The distribution of global active power across hours\n\n\n_Interpretation: There are relatively large variations of global active power from 7:00 to 21:00._\n![Box plot \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1ZZOpTtWdcetFIADhFUiUnA-1.png)\nBox plot (Image by author)\n  * Line chart: The changes in total global active power, EWMA with alpha 0.2, and EWMA with alpha 0.8 from Jan 2008 to Mar 2008\n\n\n_Interpretation: EWMA with alpha 0.8 sticks more closely to the original time series than EWMA with alpha 0.2._\n![Line chart \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1xw49_XZROcjYv7JYRIV9uQ-1.png)\nLine chart (Image by author)\nBesides, we can generate the default data profiles to display summary statistics such as count, % of missing values, and data distributions. This ensures data quality throughout the entire feature engineering process. These above visualizations can alternatively be created by the query output using Databricks SQL.\n### Wrapping it up\nIn our hands-on exploration, we used PySpark for feature engineering of time-series data using the Databricks platform:\n  * Ingesting static and streaming data, by using the `spark.read()` and `spark.readStream()` methods respectively.\n  * Manipulating and exploring data, by using a range of basic PySpark functions available in `pyspark.sql.functions`, and DataFrame methods.\n  * Extract trend-related features, by calculating the relationship within groups of data using `pyspark.sql.Window`.\n  * Visualization, by using the built-in features of Databricks Notebook.\n\n\nWhen dealing with a massive dataset, PySpark is often preferred over Pandas due to its scalability and performance capabilities. PySpark's support for lazy evaluation also means that computations are only performed when necessary, which reduces the overhead. However, Scala can sometimes be a better option, because we can closely catch up with the latest features as Spark itself is written in Scala. And more likely that systems which are less error-prone can be designed with the use of immutable objects. Different languages or libraries have their edges. Ultimately, the choice depends on the enterprise requirements, developers' learning curves, and integration with other systems.\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, and Machine Learning Operations (MLOps) demonstrations methodologies.\n> [**Performing Customer Analytics with LangChain and LLMs**](https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5)\n> [**Managing the Technical Debts of Machine Learning Systems**](https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d)\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 Science](https://towardsdatascience.com/tag/data-science/)[Databricks](https://towardsdatascience.com/tag/databricks/)[Python](https://towardsdatascience.com/tag/python/)[Spark](https://towardsdatascience.com/tag/spark/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&title=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&title=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ffeature-engineering-for-time-series-using-pyspark-on-databricks-02b97d62a287%2F&text=Feature%20Engineering%20for%20Time-Series%20Using%20PySpark%20on%20Databricks)\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/2024/09/1Z9ExsHBTNeZ6CTSaB-muXg.png)](https://towardsdatascience.com/your-pathway-to-success-how-you-can-land-a-machine-learning-and-data-science-internship-c14825b58420/)\n## [Your Pathway to Success: How You Can Land a Machine Learning and Data Science Internship](https://towardsdatascience.com/your-pathway-to-success-how-you-can-land-a-machine-learning-and-data-science-internship-c14825b58420/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAdvice and tips from a data scientist who landed two internships in a year\n[Sara Nobrega](https://towardsdatascience.com/author/saranobregafn/)\nSeptember 4, 202415 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/05/0Nh49erVct_iGbxTw-scaled.jpg)](https://towardsdatascience.com/how-python-enumerations-make-data-configuration-elegant-a7d8356657bd/)\n## [How Python Enumerations Make Data Configuration Elegant](https://towardsdatascience.com/how-python-enumerations-make-data-configuration-elegant-a7d8356657bd/)\n[Programming](https://towardsdatascience.com/category/programming/)\nAn introduction to using Enums in Python for ML projects\n[Eirik Berge](https://towardsdatascience.com/author/ebbeberge/)\nMay 28, 20238 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/17DVlEYy8x1MjiPtr3Hm6rQ.png)](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-how-to-track-data-quality-and-integrity-391435c8a299/)\n## [Monitoring Machine Learning Models in Production: How to Track Data Quality and Integrity?](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-how-to-track-data-quality-and-integrity-391435c8a299/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAs the saying goes: garbage in is garbage out. Input data quality is the most crucial component of a machine learning system. Whether or...\n[Emeli Dral](https://towardsdatascience.com/author/emeli.dral/)\nJanuary 19, 202113 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/03/1gtczkBCBj7gsNaTOJMTMpQ-scaled.jpeg)](https://towardsdatascience.com/10-free-tools-to-instantly-get-started-with-data-visualisation-d7fadb5f6dce/)\n## [10 Free tools to get started with Data Visualisation-Easily & Instantly.](https://towardsdatascience.com/10-free-tools-to-instantly-get-started-with-data-visualisation-d7fadb5f6dce/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nJump right into the Data Visualisation process with these easy and intuitive tools.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nMarch 12, 20199 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/1hbXCMuSa3x42LiqrA06ujg-scaled.jpeg)](https://towardsdatascience.com/how-to-cross-validate-your-panel-data-in-python-9ad981ddd043/)\n## [How to cross validate your panel data in Python](https://towardsdatascience.com/how-to-cross-validate-your-panel-data-in-python-9ad981ddd043/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn introduction to panel data cross validation using PanelSplit\n[Eric Frey](https://towardsdatascience.com/author/eric.frey/)\nMarch 8, 20245 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/01nCUsq5PMEuN4Qs3-scaled.jpg)](https://towardsdatascience.com/data-science-workflows-with-the-targets-package-in-r-end-to-end-example-with-code-1e31318074c4/)\n## [Data science workflows with the Targets package in R : End-to-end example with code](https://towardsdatascience.com/data-science-workflows-with-the-targets-package-in-r-end-to-end-example-with-code-1e31318074c4/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nStructured and reproducible approach for analysis\n[Prateek Bhatnagar](https://towardsdatascience.com/author/prateek-bhatnagar89/)\nAugust 19, 20213 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2018/03/1a4u9hP8sRmZKu-sZ6BTrDg.png)](https://towardsdatascience.com/why-you-should-start-using-npy-file-more-often-df2a13cc0161/)\n## [Why you should start using .npy file more often...](https://towardsdatascience.com/why-you-should-start-using-npy-file-more-often-df2a13cc0161/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nNative NumPy objects in Python provides speed advantage over regular objects. It works for as simple a task as reading data from file.\n[Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\nMarch 20, 20186 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/02/0lEDuL8gEcnShJm58-scaled.jpg)](https://towardsdatascience.com/recreating-a-538-elections-plot-making-custom-matplotlib-visualizations-b6ede7a406b4/)\n## [Recreating a 538 election's plot: making custom matplotlib visualizations](https://towardsdatascience.com/recreating-a-538-elections-plot-making-custom-matplotlib-visualizations-b6ede7a406b4/)\n[Programming](https://towardsdatascience.com/category/programming/)\nI have recently been interested in making highly customizable visualizations. Here is one example of trying to recreate 538's election...\n[Dea Bardhoshi](https://towardsdatascience.com/author/deabardhoshi/)\nFebruary 22, 20222 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/10/1wL-o4hn94uXq6rq_YLnNGg.jpeg)](https://towardsdatascience.com/the-data-scientist-who-rules-the-data-science-for-good-competitions-on-kaggle-ab436595a29f/)\n## [The Data Scientist who rules the 'Data Science for Good' competitions on Kaggle.](https://towardsdatascience.com/the-data-scientist-who-rules-the-data-science-for-good-competitions-on-kaggle-ab436595a29f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn conversation with Shivam Bansal: A Data Scientist, a Kaggle Kernel's Grandmaster, and three times winner of Kaggle's Data Science for...\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nOctober 18, 20197 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/8888feac2415/pages/",
  "body_markdown_path": "attachments/8888feac2415/pages/archived-body.md",
  "local_html": "attachments/8888feac2415/pages/archived-body.html",
  "body_source": "prior_capture"
}