avatarJohn Loewen, PhD

Summary

The article discusses how GPT-4 can revolutionize Python programming by automating tasks such as data cleaning, visualization, web scraping, and dashboard prototyping, thereby allowing developers to focus on higher-level conceptual work.

Abstract

The article titled "Level Up Your Coding with ChatGPT: 4 Real-world Python Examples" illustrates the transformative impact of GPT-4 on Python programming. It showcases four practical examples where GPT-4 significantly enhances productivity: data cleaning by filtering null values and standardizing text, data visualization through generating bar charts, web scraping to extract information from Reddit, and rapid dashboard prototyping using Dash and Plotly. The author emphasizes that GPT-4 not only saves time by handling low-level syntax but also enables developers to engage more with creative and strategic aspects of their projects. The article also provides direct code examples generated by GPT-4, demonstrating its ability to produce ready-to-use Python scripts.

Opinions

  • The author believes that GPT-4 can fundamentally change coding workflows by reducing the time spent on mundane tasks.
  • GPT-4 is seen as an effective tool for converting high-level prompts into functional Python code, streamlining the development process.
  • The author suggests that mastering the art of prompting is key to fully leveraging GPT-4's capabilities.
  • There is an opinion that GPT-4 can significantly accelerate software development, making it more efficient and cost-effective.
  • The article implies that GPT-4 allows developers to shift their focus from low-level syntactical issues to more important conceptual aspects of programming.
  • The author promotes the idea of using GPT-4 to create comprehensive data visualizations, which can be particularly useful for data analysis and presentation.
  • The author encourages readers to engage with GPT-4 and other AI tools, offering resources and further reading on the topic.

Level Up Your Coding with ChatGPT: 4 Real-world Python Examples

Eliminating low-level syntax drudgery by leveraging ChatGPT

Dall-E image: minimalist surreal image — disruption in programming due to the emergence of AI

Leveraging GPT-4 can fundamentally transform your coding workflow.

Sifting through nit-picky syntax and wrestling with data cleaning can often sidetrack us from the more conceptual aspects of programming. By deploying GPT-4, these tasks are simplified; GPT converts your prompts into workable Python code. This immediately shifts your focus from low-level drudgery to higher level thinking.

How can we best take advantage of this tool?

Here are four real-world examples illustrating GPT-4’s capabilities in diverse coding scenarios.

Example 1. Data Cleaning

In a recent project, I was working with a messy dataset of customer reviews (“reviews.csv”).

There were four columns: ‘CustomerID’, ‘Review’, ‘Rating’, and ‘Date’.

The ‘Review’ column was filled with null values and no standards for capitalization. The ‘Rating’ column had a bunch of zeros. Instead of manually writing a script, I decided to prompt GPT-4 to see if it could sort this out for me.

Prompt to ChatGPT: Using a file called ‘reviews.csv’, generate Python code to perform the following tasks: Read the CSV file into a pandas DataFrame. Remove any rows with null values in the ‘Review’ column. Convert all strings in the ‘Review’ column to lowercase. Replace all zeros in the ‘Rating’ column with the mean of the rest of the values in that column.

GPT-4’s response: Certainly, here’s some code to complete the tasks:

import pandas as pd

# Load the data
df = pd.read_csv('reviews.csv')

# Remove rows with null values in 'Review' column
df = df[df['Review'].notna()]

# Convert all strings in 'Review' column to lowercase
df['Review'] = df['Review'].str.lower()

# Calculate the mean of 'Rating' column excluding zeros
mean_rating = df[df['Rating'] != 0]['Rating'].mean()

# Replace all zeros in 'Rating' column with the mean
df['Rating'] = df['Rating'].replace(0, mean_rating)

The script uses pandas to read the CSV file, dropna() to remove null values, str.lower() to convert strings to lowercase, and a combination of replace() and mean() to replace zeros with column means.

The code was ready for immediate use, saving me an insane amount of time — time that would have been spent fiddling with syntax.

Example 2: Data Visualization

In another project, I needed to visualize the distribution of customer ratings through a bar chart.

The ratings were stored in a pandas DataFrame named ‘df’, in a column named ‘Ratings’. Rather than trying to hammer out a matplotlib script, I prompted GPT-4.

Prompt to ChatGPT: Write Python code using matplotlib to create a bar chart that represents the distribution of the ‘Ratings’ column in the DataFrame ‘df’.

GPT-4 responded with a Python script employing matplotlib’s pyplot module to create a bar chart. Here's the exact code it generated:

import matplotlib.pyplot as plt

# Generate a bar chart
plt.figure(figsize=(10, 6))
plt.hist(df['Ratings'], bins=range(1, 6), edgecolor='black', alpha=0.7)
plt.title('Distribution of Ratings')
plt.xlabel('Ratings')
plt.ylabel('Frequency')
plt.show()

The Python script employs thematplotlib’s pyplot module to create a bar chart. The code not only generates the bar chart but also sets an appropriate figure size, adds edge coloring for clarity, sets the transparency level (alpha), and includes title and labels.

Super cool, and super (insanely?) easy.

Example 3: Scraping Website Information

Recently, I needed to scrape data from a Reddit thread to collect some insights for my research. The goal was to extract the title, score, and the number of comments from the top posts in the ‘Python’ subreddit. Rather than trying to write the script myself, I asked GPT-4.

Prompt to ChatGPT: Write a Python script using PRAW (Python Reddit API Wrapper) to scrape the title, score, and the number of comments from the top 10 ‘hot’ posts in the ‘Python’ subreddit.

ChatGPTs Response: Certainly, here’s the code:

import praw
# Define the user agent, client id, client secret, and username and password
reddit = praw.Reddit(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    user_agent='YOUR_APP_NAME',
    username='YOUR_USERNAME',
    password='YOUR_PASSWORD'
)
# Get the top 10 hot posts from the Python subreddit
hot_posts = reddit.subreddit('Python').hot(limit=10)
for post in hot_posts:
    print("Title: ", post.title)
    print("Score: ", post.score)
    print("Number of Comments: ", post.num_comments)
    print("------------------\n")

To use this script, you can replace 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', 'YOUR_APP_NAME', 'YOUR_USERNAME', and 'YOUR_PASSWORD' with your Reddit app's credentials.

It pulls the desired data in seconds, saving time and effort in navigating the Reddit API yourself.

Example 4. Rapid Dashboard Prototyping

GPT-4 demonstrated proficiency in using Dash and Plotly libraries to create a dynamic, data-driven dashboard.

Recently, I wrote an article on this, found HERE.

The initial task involved generating a choropleth world map of internet usage, including a slider for yearly data selection. The interactivity of the map was enabled using Dash’s callback functions, allowing the map to update with the slider value.

On receiving a request for modification, GPT-4 swiftly added a bar chart for average internet usage by continent using Plotly’s Bar module. This required processing a new CSV file to correctly map countries to continents and calculate continent-wise averages. GPT-4 ensured a balanced visualization by appropriately dividing the display between the map and bar chart.

Python Plotly Dash app with a slider (by Year), updating both map and bar chart.

The final Python code, generated by GPT-4, integrated all these elements into a single Dash app. This showcases how GPT-4 can help in creating comprehensive data visualizations, massively accelerating software development.

In Summary…

GPT-4 offers Python developers an innovative way to streamline coding tasks.

Whether it’s data cleaning, data visualization, or rapid prototyping, GPT-4 proves to be an effective tool.

By mastering the art of prompting, developers can leverage GPT-4’s capabilities to their full extent, saving hassle, time, and money AND allowing you to focus on higher level thinking, rather than low-level syntactical drudgery.

Before you go… If you want to start writing on Medium yourself and earn money passively you only need a membership for $5 a month. If you sign up with my link, you support me with a part of your membership fee without additional costs.

If you’re interested, here’s a link to more articles I’ve written. There’s articles on Python, Generative AI, Expat living, Marathon training, Travel, and more!

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Python
Programming
Prototyping
ChatGPT
AI
Recommended from ReadMedium