Dev Tools

Python Script Builder

Make a Python script by snapping blocks together, pip packages included. Every block says what it does in plain English and shows the code it adds, and the imports and pip install line write themselves.

Needs Python from python.org (tick "Add python.exe to PATH" when installing). Blocks marked (pip) need their packages installed first: the Install & run .bat button does that for you. Read through a script before running it, and keep backups before deleting things.

Keeps this tool on this device so it works without internet, even after a refresh.

Had fun, or did this help? I’d appreciate any donation :) Not needed, but money buys temporary happiness at least lol

How to use Python Script Builder

  1. Find a block. Each one says what it does in plain English and shows the code it adds. Search works too, like "excel", "download" or "click". They're along the bottom of the tool; on a phone, tap Blocks to open them.
  2. Drag it into your script, or tap it to add it. Tap a block in your script first and new blocks go right after it. Tap the "then" or "do this each time" strip of an if, loop or function and they go inside it.
  3. Fill in the boxes. Plain text boxes become Python text for you, quotes and all. Boxes for values take Python as it is, so text there needs quotes, like "yes".
  4. Press Download .py. If the script uses packages from pip, Install & run .bat gives you a .bat that installs them and starts the script, so double-clicking it is all it takes.

You never write import lines. Each block knows what it needs, and the imports appear at the top of the file by themselves, with the pip install line above them when a package is needed. Indenting is done for you too: whatever you drop inside an if or a loop gets its four spaces, and an empty one gets a pass so the file still runs.

Click into a box and a list of your variables pops up under it, including the loop's own variable when you're inside a loop. In a text box a variable goes in as {name}, which Python fills in with its value; in a value box it goes in as just the name. If a box uses a name nothing in the script sets, the block says so, which catches most typos before you run anything.

Move blocks by dragging their ⠿ handle, or tap a block and use its arrows. Ctrl+Z undoes and Ctrl+Y redoes. With a block highlighted, Delete removes it, Ctrl+D copies it, Alt+↑ and Alt+↓ move it, and Esc lets go. The ▾ on an if, loop or other block that holds blocks folds it to one line, so long scripts are easier to get around; the code doesn't change.

The ⊘ button turns a block off: it stays in place, greyed out, and its code becomes a # comment. Blocks that delete files or folders, close programs or shut the PC down get a red edge, and ticking ask y/n first makes the script stop and ask before that step.

For quick Windows jobs like opening apps, cleaning temp files or running commands, a .bat file can be simpler: the Batch File Builder works the same way.

Already have some Python? Paste Python turns simple lines into blocks and brings ifs, loops and functions in whole as "Several lines of code" blocks, so nothing changes.

Packages from pip

Four groups cover the packages people reach for most, with blocks written in plain English: requests and BeautifulSoup for downloading pages and APIs, pandas and openpyxl for Excel and CSV, Pillow and pypdf for images and PDFs, and pyautogui, keyboard and psutil for controlling the PC.

Pick one of those groups and it also lists every command in those packages: every function, and every method of the things you work with, like a pandas table (df), an Excel sheet (ws), an image (img) or a PDF reader. Those come straight from each package's own code, so their descriptions are the package's own, and each shows which version it was read from.

Need something else? Under Any package from PyPI, type a package's pip name and the page reads that package and turns its functions and classes into blocks. Only the name you type is sent, to pypi.org, and the package itself is read in your browser.

Every block and what it does

All 182 ready-made blocks, with the code each one makes using its starting values. Imports aren't shown here; the builder adds them at the top of the file. Open a group to see them.

Basics 13
BlockCodeWhat it does
Show a messageprint("Hello!")Prints a line of text. Put a variable in curly brackets, like Hi {name}, and its value gets filled in.
Show a valueprint(total)Prints a variable or any value as it is, like a list or a number.
Empty lineprint()Prints an empty line, handy for spacing out messages.
Ask for textname = input("What is your name? ")Waits for the person running the script to type something and press Enter, and saves what they typed.
Ask for a numberwhile True:
try:
age = int(input("How old are you? "))
break
except ValueError:
print("Please type a number.")
Asks for a number and keeps asking until a real number is typed, so the script can do maths with it.
Ask yes or nosure = input("Carry on? (y/n) ").strip().lower().startswith("y")Asks a question that's answered with y or n. The variable is True for yes, so "If (any condition)" with just its name works.
Pick from a menuoptions = ["Start", "Settings", "Quit"]
for i, option in enumerate(options, 1):
print(f"{i}. {option}")
while True:
pick = input("Pick a number: ").strip()
if pick.isdigit() and 1 <= int(pick) <= len(options):
choice = options[int(pick) - 1]
break
print("Please type one of the numbers.")
Prints a numbered list and keeps asking until one of the numbers is typed. The variable holds the item picked, so "If the answer is" can check it.
Note to yourself# What this part doesA comment. Python skips it, it is only there to explain the script to whoever reads it.
Wait some secondstime.sleep(2)Pauses the script. Decimals work, like 0.5 for half a second.
Wait for Enterinput("Press Enter to close...")Waits until Enter is pressed. Without it, a script that was double-clicked closes the moment it ends, before you can read anything.
Stop the scriptsys.exit(0)Ends the script right away. 0 means everything went fine, anything else means something failed.
Run when started directlyif __name__ == "__main__":
…
The blocks inside only run when you start this file yourself, not when another script imports it. Most bigger scripts put their main steps here.
Clear the screenos.system("cls" if os.name == "nt" else "clear")Wipes the terminal window, on Windows, Mac and Linux.
Variables & lists 24
BlockCodeWhat it does
Set a variabletotal = 0Saves a value under a name. Text needs quotes, like "hello"; numbers don't, like 5. You can also do maths here, like price * 2.
Set some textgreeting = "Hello there"Saves some text under a name, with the quotes added for you. {other_variable} inside gets filled in.
Change a numbertotal += 1Adds, takes away, multiplies or divides the number in a variable, like adding 1 to a counter.
Turn into a number or textcount = int(count)Turns text like "42" into a number you can do maths with (it stops with an error if the text isn't a number), or turns a number into text so it can be joined onto other text.
Round a numberprice = round(price, 2)Rounds a number, like 3.14159 to 3.14.
Random numberroll = random.randint(1, 6)Picks a random whole number. Both ends can come up.
Pick a random itemwinner = random.choice(names)Picks one item at random from a list.
Shuffle a listrandom.shuffle(names)Mixes up the order of a list, like shuffling cards.
Make a listnames = ["Ann", "Bob", "Cara"]A list holds several values in order. Separate them with commas; text needs quotes. Leave it as [] for an empty list to fill later.
Add to a listnames.append("Dan")Puts a value on the end of a list.
Remove from a listif "Bob" in names:
names.remove("Bob")
Takes the first matching value out of a list, if it's there.
Sort a listnames.sort()Puts a list in order: A to Z for text, smallest first for numbers.
Count itemshow_many = len(names)How many items a list has, or how many letters a piece of text has.
Add up a listresult = sum(scores)The total, average, smallest or biggest of a list of numbers.
Make a dictionaryperson = {"name": "Ann", "age": 30}A dictionary stores values under names (keys), like a contact card: {"name": "Ann", "age": 30}. Leave it as {} for an empty one.
Set a dictionary valueperson["city"] = "Leeds"Stores a value under a key, replacing whatever was there.
Get a dictionary valuecity = person.get("city", "unknown")Reads the value stored under a key. If the key isn't there you get the fallback instead of an error.
Get an item by positionfirst = names[0]Takes one item out of a list by where it is: 1 is the first, 2 the second, and -1 the last.
Remove duplicatesnames = list(dict.fromkeys(names))Keeps the first copy of each item and drops the repeats, keeping the order.
Reverse a listnames.reverse()Flips the order of a list, so the last item comes first.
Keep matching itemslong_names = [n for n in names if len(n) > 3]Makes a new list with only the items that pass a check, like every name longer than 3 letters or every number over 10.
Change every itemloud = [n.upper() for n in names]Makes a new list by doing the same thing to every item, like making every name uppercase or doubling every number.
Remove a dictionary keyperson.pop("city", None)Takes a key and its value out of a dictionary. Nothing happens if it isn't there.
Use a top-level variableglobal totalInside a function, lets you change a variable that was set outside it. Put it at the start of the function.
Text 12
BlockCodeWhat it does
Change letter caseshout = name.upper()Makes text all capitals, all small letters, or Title Case.
Trim spacesanswer = answer.strip()Removes spaces and line breaks from the start and end of some text. Good for cleaning up typed answers.
Replace in textline = line.replace("cat", "dog")Swaps every copy of some text for something else.
Split text into a listparts = line.split(",")Cuts text into a list of pieces wherever the separator appears, like splitting "a,b,c" at commas. Leave the separator empty to split at spaces.
Join a list into textline = ", ".join(str(x) for x in names)Glues a list of text back together, with something in between each item.
Format a numbershown = format(total, ",.2f")Turns a number into tidy text: with commas, as money, or as a percent.
Find with a patternfound = re.findall(r"\d+", text)Finds every bit of text that matches a regular expression, like every email address or number. The Regex Tester tool helps write patterns.
Replace with a patternclean = re.sub(r"\s+", " ", text)Like Replace in text, but with a regular expression, so you can swap things like every run of spaces or every number.
If text starts or ends withif name.endswith(".pdf"):
…
else:
…
Checks the start or end of some text, like whether a file name ends with .pdf or a line starts with #.
Count how many timeserrors = text.count("error")Counts how often some text appears inside other text, like how many times "error" is in a log.
Take part of text or a listshort = text[:10]Keeps just the start or the end, or skips the start: the first 10 letters of some text, or the last 5 items of a list.
Line up textcell = str(name).ljust(20)Pads text with spaces to a set width so things line up in columns when printed.
Maths 8
BlockCodeWhat it does
Square rootroot = math.sqrt(9)The number that times itself gives this one, like 3 for 9.
Powerresult = 2 ** 10A number times itself a number of times, like 2 to the power of 10 for 1024.
Percentagepct = round(done / total * 100, 1)What percent one number is of another, rounded to one decimal place, like 45 of 60 is 75.0.
Divide with a remainderhours, minutes = divmod(125, 60)Whole-number division plus what's left over, like 125 minutes being 2 hours and 5 minutes.
Round up or downboxes = math.ceil(items / 6)Rounds always up (3.1 to 4) or always down (3.9 to 3), unlike normal rounding.
Smaller or bigger of twobest = max(score, best)Picks the smaller or the bigger of two numbers.
Keep a number in a rangevolume = max(0, min(100, volume))Stops a number going below a minimum or above a maximum, like keeping a volume between 0 and 100.
If a number is evenif n % 2 == 0:
…
else:
…
Checks whether a whole number is even or odd.
If & errors 10
BlockCodeWhat it does
Ifif age >= 18:
…
else:
…
Runs the blocks inside only when the comparison is true. Text needs quotes, like answer == "yes". The "otherwise" part is optional.
If the answer isif answer.strip().lower() == "yes":
…
else:
…
Checks typed text against a word, ignoring spaces at the ends. Handy right after "Ask for text".
If (any condition)if total > 100 and not done:
…
else:
…
Write any condition, like age > 12 and age < 20, or "@" in email.
If text containsif "error" in line:
…
else:
…
Checks whether some text appears anywhere inside other text.
If a file or folder existsif os.path.exists("notes.txt"):
…
else:
…
Runs the blocks inside only if the path is there (or isn't).
Try, and catch errorstry:
…
except Exception as e:
…
finally:
…
Runs the blocks inside, and if one of them hits that kind of error the script jumps to the "if it fails" part instead of crashing. Pick "any error" to catch everything. The error is in the variable e.
Try several timesfor attempt in range(1, 4):
try:
…
break
except Exception as e:
print(f"Try {attempt} failed: {e}")
if attempt == 3:
raise
time.sleep(5)
Runs the blocks inside, and if they hit an error, waits and tries again. Good for flaky things like downloads. After the last try the error stops the script.
Show the errorprint("Something went wrong:", e)Inside the "if it fails" part of a try block, prints what went wrong.
Stop with an errorraise ValueError("That number is too big")Stops the script (or jumps to the nearest "if it fails") with your own error message.
Do nothingpassA placeholder for a part you haven't written yet. Python needs something inside every if, loop and function.
Loops 10
BlockCodeWhat it does
Repeat a number of timesfor i in range(5):
…
Runs the blocks inside a set number of times. The counter starts at 0.
Countfor n in range(1, 11):
…
Counts with a number going up (or down with a negative step). Both ends are included.
For each item in a listfor name in names:
…
Runs once for every item in a list. Tick "numbered" to also get its position in the variable i, starting at 1.
For each key in a dictionaryfor key, value in person.items():
…
Goes through a dictionary, giving you each key and the value stored under it.
For each line of a filewith open("list.txt", encoding="utf-8") as f:
for line in f:
line = line.rstrip("\n")
…
Reads a text file one line at a time. The line break at the end of each line is removed for you.
For each file in a folderfor file in Path(".").glob("*.txt"):
if not file.is_file():
continue
…
Goes through every file that matches, like *.jpg. Inside, the variable is a path: .name is the file name, .stem the name without extension, .suffix the extension.
Repeat whilewhile tries < 3:
…
Keeps running the blocks inside for as long as the condition is true. Make sure something inside changes it, or it never stops.
Repeat foreverwhile True:
…
time.sleep(5)
Runs the blocks inside again and again until you close the window or press Ctrl+C. Use "Leave the loop" to stop it from inside.
Leave the loopbreakJumps out of the loop it's in, straight to whatever comes after the loop.
Skip to the next onecontinueSkips the rest of this round of the loop and starts the next one.
Functions 3
BlockCodeWhat it does
Make a functiondef greet(who):
…
Saves some blocks under a name so you can run them whenever you like with "Run a function". The things it takes are variables inside it, separated by commas; leave it empty if it takes nothing.
Give back a valuereturn resultEnds the function and hands a value back to whatever ran it.
Run a functiongreet("Ann")Runs a function you made, or any Python function. Put what it needs in the box, separated by commas. Give the result a name to keep what it gives back, or leave that empty.
Files & folders 25
BlockCodeWhat it does
Read a text filewith open("notes.txt", encoding="utf-8") as f:
text = f.read()
Reads a whole text file into a variable.
Read a file as a list of lineswith open("list.txt", encoding="utf-8") as f:
lines = [line.strip() for line in f if line.strip()]
Reads a text file into a list, one item per line, with empty lines left out.
Write to a text filewith open("log.txt", "a", encoding="utf-8") as f:
f.write("Done\n")
"Replace" makes a fresh file each time; "Add" puts the text on the end of what is already there, good for logs. {variables} in the text get filled in.
Save a list to a filewith open("names.txt", "w", encoding="utf-8") as f:
f.write("\n".join(str(x) for x in names) + "\n")
Writes every item of a list into a text file, one per line.
Make a folderos.makedirs("output", exist_ok=True)Creates a folder, and any folders above it that are missing. It's fine if it already exists.
Copy a fileshutil.copy2("notes.txt", "backup")Copies a file, keeping its dates. The destination can be a folder or a new file name.
Copy a whole foldershutil.copytree("project", "project-backup", dirs_exist_ok=True)Copies a folder with everything in it. Files already in the destination get replaced.
Move or renameshutil.move("old.txt", "new.txt")Moves a file or folder, or renames it if you give a new name in the same place.
Delete a fileif os.path.exists("old.txt"):
os.remove("old.txt")
Deletes a file for good. It doesn't go to the Recycle Bin. Nothing happens if it isn't there.
Delete a foldershutil.rmtree("temp-output", ignore_errors=True)Deletes a folder with every file and folder inside it, for good. Nothing happens if it isn't there.
List filesfiles = sorted(p.name for p in Path(".").glob("*") if p.is_file())Makes a list of file names in a folder, like every .csv file.
File sizesize = round(os.path.getsize("video.mp4") / 1024 ** 2, 2)How big a file is.
Split up a pathstem = Path(file).stemPulls one part out of a path: the file name, the name without extension, the extension, or the folder it is in.
Work in the script's folderos.chdir(os.path.dirname(os.path.abspath(__file__)))Makes file names like notes.txt mean "next to this script", even when it's started from somewhere else.
A folder in your user folderdownloads = Path.home() / "Downloads"The path to your Desktop, Documents, Downloads or home folder, on any PC.
Read a JSON filewith open("settings.json", encoding="utf-8") as f:
data = json.load(f)
Reads a .json file into Python lists and dictionaries.
Save as a JSON filewith open("settings.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
Writes lists and dictionaries to a .json file, nicely indented.
Read a CSV filewith open("data.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
Reads a CSV into a list of rows. Each row is a dictionary, so row["Name"] gives the Name column. Built in, no pip needed.
Save rows to a CSVwith open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
Writes a list of dictionaries to a CSV. The keys of the first row become the column names.
Zip a foldershutil.make_archive("project-backup", "zip", "project")Packs a folder into a .zip file.
Unzipshutil.unpack_archive("download.zip", "unzipped")Extracts everything from a .zip file into a folder.
Find files containing textfound = []
for p in Path(".").rglob("*.txt"):
try:
if p.is_file() and "TODO" in p.read_text(encoding="utf-8", errors="ignore"):
found.append(p)
except OSError:
pass
Searches inside every matching file, in subfolders too, and lists the ones with that text in them.
Add a row to a CSVwith open("log.csv", "a", newline="", encoding="utf-8") as f:
csv.writer(f).writerow([now, total])
Adds one row to the end of a CSV file, making the file if it isn't there. Good for logging results over time.
When a file was changedchanged = datetime.fromtimestamp(os.path.getmtime("notes.txt")).strftime("%Y-%m-%d %H:%M")The date and time a file was last saved.
Wait until a file appearswhile not os.path.exists("report.pdf"):
time.sleep(2)
Pauses until a file shows up, like a download finishing or another program saving its output.
Time & system 18
BlockCodeWhat it does
Date and time nownow = datetime.now().strftime("%Y-%m-%d %H:%M")Today's date and time as text, in the layout you pick. Good for file names and logs.
Start a timerstart = time.perf_counter()Notes the time now, so "How long since" can tell you how many seconds something took.
How long sincetook = round(time.perf_counter() - start, 2)How many seconds have passed since a timer was started, rounded to two decimals.
Run a commandsubprocess.run("ipconfig", shell=True)Runs a program or command, the same as typing it into a terminal, and waits for it to finish.
Run a command and keep its outputoutput = subprocess.run("ipconfig", shell=True, capture_output=True, text=True).stdoutRuns a command and saves the text it prints, so you can search it or save it.
Open a file or websitewebbrowser.open("https://localscriptbox.com")Opens a website in the default browser on any PC. A file opens with the program it belongs to, on Windows.
Read a setting from the systemuser = os.environ.get("USERNAME", "")Reads an environment variable, like USERNAME or a secret API key you stored outside the script.
File dropped on the scriptdropped = sys.argv[1] if len(sys.argv) > 1 else ""When a file is dragged onto the script (or it's run with extra words after it), this is that file or word. Empty if nothing was given.
Keep a log filelogging.basicConfig(filename="script.log", level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")Sets up a log file. After this, "Write to the log" adds time-stamped lines to it.
Write to the loglogging.info("Started")Adds a time-stamped line to the log file set up by "Keep a log file".
A date from nowdue = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")The date some days ahead or back, like a due date in 14 days or a cut-off 30 days ago.
Day of the weektoday = datetime.now().strftime("%A")Today's day name, like Monday, for scripts that do different things on different days.
Wait until a time of daynow_ = datetime.now()
target = datetime.combine(now_.date(), datetime.strptime("21:00", "%H:%M").time())
if target <= now_:
target += timedelta(days=1)
time.sleep((target - now_).total_seconds())
Pauses until a time on the 24-hour clock, like 21:00. If that time has already passed today, it waits for tomorrow's.
Countdownfor left in range(10, 0, -1):
print("\r" + "Starting in" + " " + str(left) + " ", end="", flush=True)
time.sleep(1)
print()
Shows the seconds ticking down on one line, then carries on.
Copy to the clipboard (Windows)subprocess.run("clip", input="Hello from Python", text=True)Puts text on the clipboard so it can be pasted anywhere with Ctrl+V. Uses the clip command built into Windows, no pip needed.
Send an emailmsg = EmailMessage()
msg["From"] = "me@gmail.com"
msg["To"] = "friend@example.com"
msg["Subject"] = "Backup finished"
msg.set_content("All done.")
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as mail:
mail.login("me@gmail.com", os.environ.get("EMAIL_PASSWORD", ""))
mail.send_message(msg)
Sends an email through your mail provider. For Gmail, make an app password in your Google account and save it in an environment variable called EMAIL_PASSWORD, so it never sits in the script.
Shut down or restart (Windows)os.system("shutdown /s /t 60")Shuts down or restarts Windows after a countdown. "shutdown /a" in a terminal cancels it.
Beep (Windows)winsound.Beep(880, 300)Plays a short beep.
Web & scraping (pip) 11
BlockCodeWhat it does
Download a web page
pip: requests
r = requests.get("https://example.com", timeout=30)
r.raise_for_status()
html = r.text
Downloads a web page as text. Stops with an error if the site says no (like a 404).
Get data from an API
pip: requests
r = requests.get("https://api.github.com/repos/python/cpython", timeout=30)
r.raise_for_status()
data = r.json()
Calls an API and turns its JSON answer into Python lists and dictionaries. The API Request Builder tool helps work out the URL.
Send data to an API
pip: requests
r = requests.post("https://httpbin.org/post", json={"message": "hi"}, timeout=30)
r.raise_for_status()
reply = r.json()
Sends a dictionary as JSON to an API (a POST request) and keeps the answer.
Download a file
pip: requests
with requests.get("https://www.python.org/static/img/python-logo.png", stream=True, timeout=60) as r:
r.raise_for_status()
with open("python-logo.png", "wb") as f:
for chunk in r.iter_content(65536):
f.write(chunk)
Saves a file from the internet to your PC, a piece at a time, so big files work too.
If a site is up
pip: requests
try:
site_ok = requests.get("https://example.com", timeout=10).ok
except requests.RequestException:
site_ok = False
if site_ok:
…
else:
…
Runs the blocks inside if the site loads, and the "otherwise" part if it is down or too slow.
Read the HTML
pip: beautifulsoup4
soup = BeautifulSoup(html, "html.parser")Turns a page's HTML into something you can search, with BeautifulSoup. Use it after "Download a web page".
Find things on the page
pip: beautifulsoup4
titles = [el.get_text(strip=True) for el in soup.select("h2")]Finds every element matching a CSS selector, like h2, .price or a[href], and keeps their text.
Find one thing on the page
pip: beautifulsoup4
el = soup.select_one(".price")
price = el.get_text(strip=True) if el else ""
Finds the first element matching a CSS selector and keeps its text, or an empty text if there is none.
Every link on the page
pip: beautifulsoup4
links = [urljoin("https://example.com", a["href"]) for a in soup.select("a[href]")]Collects the web address of every link on the page, made into full URLs.
Page title
pip: beautifulsoup4
title = soup.title.get_text(strip=True) if soup.title else ""The text in the page's title tag, the one shown in the browser tab.
Post to a Discord webhook
pip: requests
requests.post("https://discord.com/api/webhooks/...", json={"content": "Backup finished"}, timeout=30).raise_for_status()Sends a message to a Discord channel through a webhook (Channel settings, Integrations, Webhooks). Handy for "backup finished" or "site is down" alerts.
Spreadsheets (pip) 17
BlockCodeWhat it does
Open a spreadsheet
pip: pandas, openpyxl
df = pd.read_excel("sales.xlsx")Opens a CSV or Excel file as a table with pandas. Excel files also need openpyxl, which is added for you.
Show the first rows
pip: pandas
print(df.head(5))Prints the top of a table so you can see what's in it.
Keep matching rows
pip: pandas
big = df[df["Amount"] > 100]Keeps only the rows where a column matches, like Region is "North" or Amount is more than 100. Text needs quotes.
Sort the rows
pip: pandas
df = df.sort_values("Amount", ascending=False)Puts the rows in order of one column.
Total a column
pip: pandas
total = df["Amount"].sum()The total, average, smallest, biggest or count of a column.
Totals by group
pip: pandas
by_region = df.groupby("Region")["Amount"].sum().reset_index()Adds up a column separately for each value in another, like total sales for each region. Gives a new table.
Add a column
pip: pandas
df["Total"] = df["Price"] * df["Qty"]Makes a new column worked out from others. Refer to a column as df["Name"], like df["Price"] * df["Qty"].
Remove duplicate rows
pip: pandas
df = df.drop_duplicates()Drops rows that are exact copies of an earlier row.
Combine two tables
pip: pandas
joined = orders.merge(customers, on="Customer ID", how="left")Joins two tables side by side wherever a shared column matches, like matching orders to customers by Customer ID.
Save a spreadsheet
pip: pandas, openpyxl
df.to_excel("report.xlsx", index=False)Saves a table as a CSV or Excel file, depending on the ending you give it.
For each row
pip: pandas
for _, row in df.iterrows():
…
Goes through a table one row at a time. Inside, row["Name"] is that row's Name.
Open an Excel file to edit
pip: openpyxl
wb = openpyxl.load_workbook("budget.xlsx")
ws = wb.active
Opens an .xlsx with openpyxl so you can read and change single cells, keeping its formatting. Leave the sheet empty for the first one.
New Excel file
pip: openpyxl
wb = openpyxl.Workbook()
ws = wb.active
Starts a fresh Excel workbook to fill in.
Read a cell
pip: openpyxl
value = ws["B2"].valueReads one cell, like B2.
Write a cell
pip: openpyxl
ws["B10"] = "=SUM(B2:B9)"Writes a value into one cell. Start it with = to make a formula, like "=SUM(B2:B9)".
Add a row
pip: openpyxl
ws.append(["2026-11-21", "Coffee", 3.5])Adds a row of values under the last one used.
Save the Excel file
pip: openpyxl
wb.save("budget.xlsx")Saves the workbook. Close it in Excel first or Windows won't let it be saved.
Images & PDFs (pip) 14
BlockCodeWhat it does
Open an image
pip: pillow
img = Image.open("photo.jpg")Opens a picture with Pillow so you can resize, crop or convert it.
Shrink to fit
pip: pillow
img.thumbnail((1280, 1280))Makes an image smaller so it fits inside the size, keeping its shape. It never makes it bigger.
Resize exactly
pip: pillow
img = img.resize((800, 600))Resizes to an exact size, stretching if the shape is different.
Crop
pip: pillow
img = img.crop((0, 0, 500, 500))Cuts out a rectangle, measured in pixels from the top left corner.
Rotate
pip: pillow
img = img.rotate(-90, expand=True)Turns an image without cutting off the corners.
Black and white
pip: pillow
img = img.convert("L")Turns an image into greyscale.
Write text on an image
pip: pillow
font = ImageFont.load_default(40)
ImageDraw.Draw(img).text((20, 20), "© Me", fill="white", font=font)
Draws text onto the image, like a watermark or a date. Size 0 uses the built-in small font.
Save an image
pip: pillow
img.convert("RGB").save("small.jpg", quality=85)Saves the image. The ending you give picks the format, so .png, .jpg and .webp all work. Quality matters for .jpg and .webp.
Merge PDFs
pip: pypdf
writer = PdfWriter()
for pdf in ["part1.pdf", "part2.pdf"]:
writer.append(pdf)
with open("merged.pdf", "wb") as f:
writer.write(f)
Joins several PDFs into one, in the order given. Give a list of file names, or a variable holding one.
Split a PDF into pages
pip: pypdf
reader = PdfReader("report.pdf")
for i, page in enumerate(reader.pages, 1):
writer = PdfWriter()
writer.add_page(page)
with open(f"report-page-{i}.pdf", "wb") as f:
writer.write(f)
Saves every page as its own PDF, named like report-page-1.pdf, next to the original.
Get the text from a PDF
pip: pypdf
text = "\n".join(page.extract_text() or "" for page in PdfReader("report.pdf").pages)Pulls out the text from every page. Scanned PDFs are pictures, so they come out empty.
Count PDF pages
pip: pypdf
pages = len(PdfReader("report.pdf").pages)How many pages a PDF has.
Rotate PDF pages
pip: pypdf
writer = PdfWriter()
for page in PdfReader("scan.pdf").pages:
writer.add_page(page.rotate(90))
with open("scan-fixed.pdf", "wb") as f:
writer.write(f)
Rotates all the pages, like fixing a scan that came out sideways.
Password-protect a PDF
pip: pypdf
writer = PdfWriter(clone_from="private.pdf")
writer.encrypt("change-me")
with open("private-locked.pdf", "wb") as f:
writer.write(f)
Saves a copy that needs a password to open. Don't lose the password, it can't be recovered.
PC automation (pip) 14
BlockCodeWhat it does
Click
pip: pyautogui
pyautogui.click(500, 400)Moves the mouse to a spot on the screen and clicks. The Screen Coordinate Finder tool tells you the numbers. Slam the mouse into a screen corner to stop a runaway script.
Move the mouse
pip: pyautogui
pyautogui.moveTo(500, 400, duration=0.3)Glides the pointer to a spot on the screen.
Type text
pip: pyautogui
pyautogui.write("Hello from Python", interval=0.02)Types text into whatever window is active, as if on the keyboard.
Press keys
pip: pyautogui
pyautogui.hotkey("ctrl", "s")Presses a key or a shortcut. Join keys with +, like ctrl+s or alt+tab; single keys like enter, tab, esc or f5 work too.
Take a screenshot
pip: pyautogui
pyautogui.screenshot("screen.png")Saves a picture of the whole screen. {now} style variables in the name help keep each one.
Find a picture on screen
pip: pyautogui
try:
spot = pyautogui.locateCenterOnScreen("button.png")
except pyautogui.ImageNotFoundException:
spot = None
Looks for a small screenshot (like a button) on the screen and gives its centre, or None if it isn't there. "Click" can then use spot[0], spot[1].
Popup message
pip: pyautogui
pyautogui.alert("Time for a break", "Reminder")Shows a small message box with an OK button and waits until it's clicked.
Wait for a hotkey
pip: keyboard
keyboard.wait("ctrl+shift+s")Pauses until a key or shortcut is pressed anywhere, even in another window.
When a hotkey is pressed
pip: keyboard
keyboard.add_hotkey("ctrl+alt+n", greet)Runs one of your functions every time a shortcut is pressed. Add "Wait for a hotkey" (like esc) after it to keep the script running.
If a program is running
pip: psutil
if "notepad.exe" in (p.info["name"].lower() for p in psutil.process_iter(["name"]) if p.info["name"]):
…
else:
…
Checks the list of running programs for a name like notepad.exe.
Close a program
pip: psutil
for p in psutil.process_iter(["name"]):
if (p.info["name"] or "").lower() == "notepad.exe":
p.kill()
Ends every running copy of a program. Unsaved work in it is lost.
CPU and memory use
pip: psutil
cpu = psutil.cpu_percent(interval=1)How busy the processor is, or how full the memory is, from 0 to 100.
Free disk space
pip: psutil
free_gb = round(psutil.disk_usage("C:\\").free / 1024 ** 3, 1)How much space is left on a drive.
Battery level
pip: psutil
b = psutil.sensors_battery()
battery = b.percent if b else None
The laptop's battery level, or None on a PC without one.
Anything else 3
BlockCodeWhat it does
Any line of codeprint("Anything goes here")Type any line of Python exactly as it should appear.
Several lines of codefor i in range(3):
print(i)
Paste or type several lines of Python. They get indented to fit wherever you put the block.
Import a moduleimport mathImports a module the other blocks don't cover. Most blocks add their own imports at the top for you.

Every built-in function

The 70 functions that come with Python itself, no import or pip needed. Each is a block in the "Every built-in function" group.

Built-in functions 70
FunctionWhat it does
abs()The size of a number without its minus sign, so -5 gives 5.
aiter()Gets an async iterator from something you can loop over with async for. Only needed in async code.
all()True if every item is true, like every box ticked. An empty list gives True.
anext()The next item from an async iterator. Only needed in async code.
any()True if at least one item is true.
ascii()Like repr, but anything that isn't plain English letters is written as a code like \xe9.
bin()A whole number written in binary, like 5 to "0b101".
bool()True or False for any value. 0, empty text, empty lists and None count as False.
breakpoint()Pauses the script here and opens the debugger, so you can look at your variables.
bytearray()Like bytes, but you can change it after making it.
bytes()Raw bytes, like the contents of an image file. "hi".encode() is the usual way to get them from text.
callable()True if something can be run with brackets, like a function.
chr()The character for a Unicode number, like 65 to "A" or 128512 to an emoji.
classmethod()Turns a method into one that works on the class itself. Mostly written as @classmethod above a def.
compile()Turns text into Python code that exec or eval can run. Rarely needed.
complex()A complex number, the kind with an imaginary part, like 2+3j.
delattr()Removes an attribute from an object by its name.
dict()Makes a dictionary, from pairs or from name=value arguments.
dir()Lists every name an object has (its attributes and methods). Great for exploring a package.
divmod()Division and remainder in one go: 17, 5 gives (3, 2).
enumerate()Pairs each item with its position, for loops that need both.
eval()Runs some text as a Python expression and gives the answer. Never use it on text from someone else: it can run anything.
exec()Runs text as Python code. Never use it on text from someone else: it can run anything.
filter()Keeps only the items the function says yes to.
float()Turns text or a whole number into a decimal number.
format()Formats a value with a spec like ",.2f" for 1,234.50.
frozenset()A set that can't be changed after it's made.
getattr()Reads an attribute by its name, with a fallback if it isn't there.
globals()A dictionary of every top-level variable in the script.
hasattr()True if an object has an attribute with that name.
hash()A number Python uses to look things up quickly in sets and dictionaries.
help()Prints the built-in help for a function, module or object.
hex()A whole number in hexadecimal, like 255 to "0xff".
id()A number that's unique to an object while it exists. Two names for the same list give the same id.
input()Waits for typing and Enter, and gives back what was typed as text.
int()Turns text or a decimal into a whole number. Decimals are cut off, not rounded.
isinstance()True if a value is of a type, like isinstance(x, str) for text.
issubclass()True if one class is built on another.
iter()Gets an iterator, so next() can take items one at a time.
len()How many items in a list, letters in text, or keys in a dictionary.
list()Makes a list from anything you can loop over, like list("abc") for ["a", "b", "c"].
locals()A dictionary of the variables in the current function.
map()Runs a function on every item, like map(str.upper, names).
max()The biggest item in a list, or of several values separated by commas. key picks what to compare, like key=len for the longest; default is given back if the list is empty.
memoryview()A view into bytes without copying them. Only needed for big binary data.
min()The smallest item in a list, or of several values separated by commas. key picks what to compare, like key=len for the shortest; default is given back if the list is empty.
next()The next item from an iterator, or the default when there are none left.
object()A plain empty object. Every class is built on it.
oct()A whole number in octal, like 8 to "0o10".
open()Opens a file to read ("r"), write ("w") or add to ("a"), as UTF-8 text so any language works. Add b to the mode, like "rb", for images and other files that aren't text. The file blocks use it with "with" so the file closes itself.
ord()The Unicode number of a character, like "A" to 65.
pow()A number to a power, like pow(2, 10) for 1024. Same as 2 ** 10.
print()Prints values to the screen. "Show a message" is the friendlier block for text.
property()Makes a method read like an attribute. Mostly written as @property above a def.
range()The numbers from start up to (not including) stop, for loops.
repr()How Python would write a value in code, with quotes around text. Handy for checking what's really in a variable.
reversed()The items in the opposite order.
round()Rounds a number, to a number of decimal places if you give one.
set()A set: like a list but every item only once, and in no particular order. Good for removing duplicates.
setattr()Sets an attribute by its name.
slice()A reusable cut like [1:5], for taking part of a list or text.
sorted()A new list in order, smallest or A first. key picks what to sort by, like key=len for shortest first. The original isn't changed.
staticmethod()Makes a method that doesn't need the object. Mostly written as @staticmethod above a def.
str()Turns anything into text.
sum()Adds up a list of numbers.
super()Inside a class, reaches the class it's built on, like super().__init__().
tuple()Like a list, but it can't be changed after it's made.
type()What kind of value something is, like int, str or list.
vars()An object's attributes as a dictionary.
zip()Pairs up items from two lists side by side, like names with their scores.

Every command in the covered packages

All 1030 functions, classes and methods of the packages above, read from their own code on PyPI. Methods work on an object you already have, like a pandas table (df) or an image (img). The descriptions are the packages' own.

requests 2.34.2 46
CommandWhat it does
requests.codes()
requests.delete(url)Sends a DELETE request.
requests.get(url, params)Sends a GET request.
requests.head(url)Sends a HEAD request.
requests.options(url)Sends an OPTIONS request.
requests.packages()
requests.patch(url, data)Sends a PATCH request.
requests.post(url, data, json)Sends a POST request.
requests.put(url, data)Sends a PUT request.
requests.request(method, url)Constructs and sends a Request <Request>.
requests.session()Returns a Session for context-management.
requests.utils()
requests.ConnectTimeout()The request timed out while trying to connect to the remote server.
requests.PreparedRequest()The fully mutable PreparedRequest <PreparedRequest> object, containing the exact bytes that will be sent to the server.
requests.ReadTimeout()The server did not send any data in the allotted amount of time.
requests.Request(method, url, headers, files, data, params, auth, cookies, hooks, json)A user-created Request <Request> object.
requests.Response()The Response <Response> object, which contains a server's response to an HTTP request.
requests.Session()A Requests session.
requests.Timeout()The request timed out.
requests.TooManyRedirects()Too many redirects.
requests.URLRequired()A valid URL is required to make a request.
r.close()Releases the connection back to the pool.
r.iter_content(chunk_size, decode_unicode)Iterates over the response data.
r.iter_lines(chunk_size, decode_unicode, delimiter)Iterates over the response data, one line at a time.
r.json()Decodes the JSON response body (if any) as a Python object.
r.raise_for_status()Raises HTTPError, if one occurred.
session.close()Closes all adapters and as such the session
session.delete(url)Sends a DELETE request.
session.get(url, params)Sends a GET request.
session.get_adapter(url)Returns the appropriate connection adapter for the given URL.
session.get_redirect_target(resp)Receives a Response.
session.head(url)Sends a HEAD request.
session.merge_environment_settings(url, proxies, stream, verify, cert)Check the environment and merge it with some settings.
session.mount(prefix, adapter)Registers a connection adapter to a prefix.
session.options(url)Sends a OPTIONS request.
session.patch(url, data)Sends a PATCH request.
session.post(url, data, json)Sends a POST request.
session.prepare_request(request)Constructs a PreparedRequest <PreparedRequest> for transmission and returns it.
session.put(url, data)Sends a PUT request.
session.rebuild_auth(prepared_request, response)When being redirected we may want to strip authentication from the request to avoid leaking credentials.
session.rebuild_method(prepared_request, response)When being redirected we may want to change the method of the request based on certain specs or browser behavior.
session.rebuild_proxies(prepared_request, proxies)This method re-evaluates the proxy configuration by considering the environment variables.
session.request(method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)Constructs a Request <Request>, prepares it and sends it.
session.resolve_redirects(resp, req, stream, timeout, verify, cert, proxies, yield_requests)Receives a Response.
session.send(request)Send a given PreparedRequest.
session.should_strip_auth(old_url, new_url)Decide whether Authorization header should be removed when redirecting
beautifulsoup4 4.15.0 80
CommandWhat it does
bs4.BeautifulSoup(markup, features, builder, parse_only, from_encoding, exclude_encodings, element_classes)A data structure representing a parsed HTML or XML document.
bs4.CData()A CDATA section <https://dev.w3.org/html5/spec-LC/syntax.html#cdata-sections>_.
bs4.Comment()An HTML comment <https://dev.w3.org/html5/spec-LC/syntax.html#comments>_ or XML comment <https://www.w3.org/TR/REC-xml/#sec-comments>_.
bs4.CSS(tag, api)A proxy object against the soupsieve library, to simplify its CSS selector API.
bs4.Declaration()An XML declaration <https://www.w3.org/TR/REC-xml/#sec-prolog-dtd>_.
bs4.Doctype()A document type declaration <https://www.w3.org/TR/REC-xml/#dt-doctype>_.
bs4.ElementFilter(match_function)ElementFilter encapsulates the logic necessary to decide:
bs4.FeatureNotFound()Exception raised by the BeautifulSoup constructor if no parser with the requested features is found.
bs4.ParserRejectedMarkup(message_or_exception)An Exception to be raised when the underlying parser simply refuses to parse the given markup.
bs4.ProcessingInstruction()A SGML processing instruction.
bs4.ResultSet(source, result)A ResultSet is a list of PageElement objects, gathered as the result of matching an :pyElementFilter against a parse tree.
bs4.Script()A NavigableString representing the contents of a <script> HTML tag <https://dev.w3.org/html5/spec-LC/Overview.html#the-script-element>_ (probably Javascript).
bs4.StopParsing()Exception raised by a TreeBuilder if it's unable to continue parsing.
bs4.Stylesheet()A NavigableString representing the contents of a <style> HTML tag <https://dev.w3.org/html5/spec-LC/Overview.html#the-style-element>_ (probably CSS).
bs4.Tag(parser, builder, name, namespace, prefix, attrs, parent, previous, is_xml, sourceline, sourcepos, can_be_empty_element, cdata_list_attributes, preserve_whitespace_tags, interesting_string_types, namespaces)An HTML or XML tag that is part of a parse tree, along with its attributes, contents, and relationships to other parts of the tree.
bs4.TemplateString()A NavigableString representing a string found inside an HTML <template> tag <https://html.spec.whatwg.org/multipage/scripting.html#the-template-element>_ embedded in a larger document.
bs4.UnicodeDammit(markup, known_definite_encodings, smart_quotes_to, is_html, exclude_encodings, user_encodings, override_encodings)A class for detecting the encoding of a bytestring containing an HTML or XML document, and decoding it to Unicode.
soup.append(tag)Appends the given PageElement to the contents of this Tag.
soup.childGenerator()Deprecated generator.
soup.clear(decompose)Destroy all children of this Tag by calling PageElement.extract on them.
soup.copy_self()Create a new BeautifulSoup object with the same TreeBuilder, but not associated with any markup.
soup.decode(indent_level, eventual_encoding, formatter, iterator)Returns a string representation of the parse tree as a full HTML or XML document.
soup.decode_contents(indent_level, eventual_encoding, formatter)Renders the contents of this tag as a Unicode string.
soup.decompose()Recursively destroys this PageElement and its children.
soup.encode(encoding, indent_level, formatter, errors)Render this Tag and its contents as a bytestring.
soup.encode_contents(indent_level, encoding, formatter)Renders the contents of this PageElement as a bytestring.
soup.endData(containerClass)Method called by the TreeBuilder when the end of a data segment occurs.
soup.extend(tags)Appends one or more objects to the contents of this Tag.
soup.extract()Destructively rips this element out of the tree.
soup.find(name, attrs, recursive, string)Look in the children of this PageElement and find the first PageElement that matches the given criteria.
soup.find_all(name, attrs, recursive, string, limit)Look in the children of this PageElement and find all PageElement objects that match the given criteria.
soup.find_all_next(name, attrs, string, limit)Find all PageElement objects that match the given criteria and appear later in the document than this PageElement.
soup.find_all_previous(name, attrs, string, limit)Look backwards in the document from this PageElement and find all PageElement that match the given criteria.
soup.find_next(name, attrs, string)Find the first PageElement that matches the given criteria and appears later in the document than this PageElement.
soup.find_next_sibling(name, attrs, string)Find the closest sibling to this PageElement that matches the given criteria and appears later in the document.
soup.find_next_siblings(name, attrs, string, limit)Find all siblings of this PageElement that match the given criteria and appear later in the document.
soup.find_parent(name, attrs)Find the closest parent of this PageElement that matches the given criteria.
soup.find_parents(name, attrs, limit)Find all parents of this PageElement that match the given criteria.
soup.find_previous(name, attrs, string)Look backwards in the document from this PageElement and find the first PageElement that matches the given criteria.
soup.find_previous_sibling(name, attrs, string)Returns the closest sibling to this PageElement that matches the given criteria and appears earlier in the document.
soup.find_previous_siblings(name, attrs, string, limit)Returns all siblings to this PageElement that match the given criteria and appear earlier in the document.
soup.format_string(s, formatter)Format the given string using the given formatter.
soup.formatter_for_name(formatter_name)Look up or create a Formatter for the given identifier, if necessary.
soup.get(key, default)Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.
soup.get_attribute_list(key, default)The same as get(), but always returns a (possibly empty) list.
soup.get_text(separator, strip, types)Get all child strings of this PageElement, concatenated using the given separator.
soup.handle_data(data)Called by the tree builder when a chunk of textual data is encountered.
soup.handle_endtag(name, nsprefix)Called by the tree builder when an ending tag is encountered.
soup.handle_starttag(name, namespace, nsprefix, attrs, sourceline, sourcepos, namespaces)Called by the tree builder when a new tag is encountered.
soup.has_attr(key)Does this Tag have an attribute with the given name?
soup.has_key(key)Deprecated method.
soup.index(element)Find the index of a child of this Tag (by identity, not value).
soup.insert(position)Insert one or more new PageElements as a child of this Tag.
soup.insert_after()This method is part of the PageElement API, but BeautifulSoup doesn't implement it because there is nothing before or after it in the parse tree.
soup.insert_before()This method is part of the PageElement API, but BeautifulSoup doesn't implement it because there is nothing before or after it in the parse tree.
soup.isSelfClosing()
soup.new_string(s, subclass)Create a new NavigableString associated with this BeautifulSoup object.
soup.new_tag(name, namespace, nsprefix, attrs, sourceline, sourcepos, string)Create a new Tag associated with this BeautifulSoup object.
soup.nextGenerator()
soup.nextSiblingGenerator()
soup.object_was_parsed(o, parent, most_recent_element)Method called by the TreeBuilder to integrate an object into the parse tree.
soup.parentGenerator()
soup.popTag()Internal method called by _popToTag when a tag is closed.
soup.prettify(encoding, formatter)Pretty-print this Tag as a string or bytestring.
soup.previousGenerator()
soup.previousSiblingGenerator()
soup.pushTag(tag)Internal method called by handle_starttag when a tag is opened.
soup.recursiveChildGenerator()Deprecated generator.
soup.renderContents(encoding, prettyPrint, indentLevel)Deprecated method for BS3 compatibility.
soup.replaceWithChildren()
soup.replace_with()Replace this PageElement with one or more other elements, objects, keeping the rest of the tree the same.
soup.reset()Reset this object to a state as though it had never parsed any markup.
soup.select(selector, namespaces, limit)Perform a CSS selection operation on the current element.
soup.select_one(selector, namespaces)Perform a CSS selection operation on the current element.
soup.setup(parent, previous_element, next_element, previous_sibling, next_sibling)Sets up the initial relations between this element and other elements.
soup.smooth()Smooth out the children of this Tag by consolidating consecutive strings.
soup.string_container(base_class)Find the class that should be instantiated to hold a given kind of string.
soup.unwrap()Replace this PageElement with its contents.
soup.wrap(wrap_inside)Wrap this PageElement inside a Tag.
element.Tag(parser, builder, name, namespace, prefix, attrs, parent, previous, is_xml, sourceline, sourcepos, can_be_empty_element, cdata_list_attributes, preserve_whitespace_tags, interesting_string_types, namespaces)An HTML or XML tag that is part of a parse tree, along with its attributes, contents, and relationships to other parts of the tree.
pandas 3.1.1 444
CommandWhat it does
pandas.api()
pandas.array(data, dtype, copy)Create an array.
pandas.arrays()
pandas.bdate_range(start, end, periods, freq, tz, normalize, name, weekmask, holidays, inclusive)Return a fixed frequency DatetimeIndex with business day as the default.
pandas.CategoricalIndex()
pandas.col(col_name)Generate deferred object representing a column of a DataFrame.
pandas.concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy, union_categories)Concatenate pandas objects along a particular axis.
pandas.crosstab(index, columns, values, rownames, colnames, aggfunc, margins, margins_name, dropna, normalize)Compute a simple cross tabulation of two (or more) factors.
pandas.cut(x, bins, right, labels, retbins, precision, include_lowest, duplicates, ordered)Bin values into discrete intervals.
pandas.date_range(start, end, periods, freq, tz, normalize, name, inclusive, unit, ambiguous, nonexistent)Return a fixed frequency DatetimeIndex.
pandas.DateOffset()
pandas.DatetimeIndex()
pandas.errors()
pandas.eval(expr)Evaluate a Python expression as a string using various backends.
pandas.factorize(values, sort, use_na_sentinel, size_hint)Encode the object as an enumerated type or categorical variable.
pandas.from_dummies(data, sep, default_category)Create a categorical DataFrame from a DataFrame of dummy variables.
pandas.get_dummies(data, prefix, prefix_sep, dummy_na, columns, sparse, drop_first, dtype)Convert categorical variable into dummy/indicator variables.
pandas.Index()
pandas.IndexSlice()
pandas.infer_freq(index)Infer the most likely frequency given the input index.
pandas.Interval()
pandas.interval_range(start, end, periods, freq, name, closed)Return a fixed frequency IntervalIndex.
pandas.IntervalIndex()
pandas.io()
pandas.isna(obj)Detect missing values for an array-like object.
pandas.isnull()
pandas.json_normalize(data, record_path, meta, meta_prefix, record_prefix, errors, sep, max_level)Normalize semi-structured JSON data into a flat table.
pandas.lreshape(data, groups, dropna)Reshape wide-format data to long.
pandas.melt(frame, id_vars, value_vars, var_name, value_name, col_level, ignore_index)Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
pandas.merge(left, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)Merge DataFrame or named Series objects with a database-style join.
pandas.merge_asof(left, right, on, left_on, right_on, left_index, right_index, by, left_by, right_by, suffixes, tolerance, allow_exact_matches, direction)Perform a merge by key distance.
pandas.merge_ordered(left, right, on, left_on, right_on, left_by, right_by, fill_method, suffixes, how)Perform a merge for ordered data with optional filling/interpolation.
pandas.MultiIndex()
pandas.NamedFunc()
pandas.NaT()
pandas.notna(obj)Detect non-missing values for an array-like object.
pandas.notnull()
pandas.offsets()
pandas.options()
pandas.Period()
pandas.period_range(start, end, periods, freq, name)Return a fixed frequency PeriodIndex.
pandas.PeriodIndex()
pandas.pivot(data, columns, index, values)Return reshaped DataFrame organized by given index / column values.
pandas.pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name, observed, sort)Create a spreadsheet-style pivot table as a DataFrame.
pandas.plotting()
pandas.qcut(x, q, labels, retbins, precision, duplicates)Quantile-based discretization function.
pandas.RangeIndex()
pandas.read_clipboard(sep, dtype_backend)Read text from clipboard and pass to ~pandas.read_csv.
pandas.read_csv(filepath_or_buffer, sep, delimiter)Read a comma-separated values (csv) file into DataFrame.
pandas.read_excel(io, sheet_name, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_format, thousands, decimal, comment, skipfooter, storage_options, dtype_backend, engine_kwargs)Read an Excel file into a DataFrame.
pandas.read_feather(path, columns, use_threads, storage_options, dtype_backend)Load a feather-format object from the file path.
pandas.read_fwf(filepath_or_buffer, colspecs, widths, infer_nrows, iterator, chunksize)Read a table of fixed-width formatted lines into DataFrame.
pandas.read_hdf(path_or_buf, key, mode, errors, where, start, stop, columns, iterator, chunksize)Read from the store, close it if we opened it.
pandas.read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, thousands, encoding, decimal, converters, na_values, keep_default_na, displayed_only, extract_links, dtype_backend, storage_options)Read HTML tables into a list of DataFrame objects.
pandas.read_iceberg(table_identifier, catalog_name, catalog_properties, columns, row_filter, case_sensitive, snapshot_id, limit, scan_properties)Read an Apache Iceberg table into a pandas DataFrame.
pandas.read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, precise_float, date_unit, encoding, encoding_errors, lines, chunksize, compression, nrows, storage_options, dtype_backend, engine)Convert a JSON string to pandas object.
pandas.read_orc(path, columns, dtype_backend, filesystem)Load an ORC object from the file path, returning a DataFrame.
pandas.read_parquet(path, engine, columns, storage_options, dtype_backend, filesystem, filters, to_pandas_kwargs)Load a parquet object from the file path, returning a DataFrame.
pandas.read_pickle(filepath_or_buffer, compression, storage_options)Load pickled pandas object (or any object) from file and return unpickled object.
pandas.read_sas(filepath_or_buffer, format, index, encoding, chunksize, iterator, compression)Read SAS files stored as either XPORT or SAS7BDAT format files.
pandas.read_spss(path, usecols, convert_categoricals, dtype_backend)Load an SPSS file from the file path, returning a DataFrame.
pandas.read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize, dtype_backend, dtype)Read SQL query or database table into a DataFrame.
pandas.read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize, dtype, dtype_backend)Read SQL query into a DataFrame.
pandas.read_sql_table(table_name, con, schema, index_col, coerce_float, parse_dates, columns, chunksize, dtype_backend)Read SQL database table into a DataFrame.
pandas.read_stata(filepath_or_buffer, convert_dates, convert_categoricals, index_col, convert_missing, preserve_dtypes, columns, order_categoricals, chunksize, iterator, compression, storage_options)Read Stata file into DataFrame.
pandas.read_table(filepath_or_buffer, sep, delimiter)Read general delimited file into DataFrame.
pandas.read_xml(path_or_buffer, xpath, namespaces, elems_only, attrs_only, names, dtype, converters, parse_dates)Read XML document into a ~pandas.DataFrame object.
pandas.set_eng_float_format(accuracy, use_eng_prefix)Format float representation in DataFrame with SI notation.
pandas.Timedelta()
pandas.timedelta_range(start, end, periods, freq, name, closed, unit)Return a fixed frequency TimedeltaIndex with day as the default.
pandas.TimedeltaIndex()
pandas.Timestamp()
pandas.to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, origin, cache)Convert argument to datetime.
pandas.to_numeric(arg, errors, downcast, dtype_backend)Convert argument to a numeric type.
pandas.to_pickle(obj, filepath_or_buffer, compression, protocol, storage_options)Pickle (serialize) object to file.
pandas.to_timedelta(arg, unit, errors)Convert argument to timedelta.
pandas.tseries()
pandas.unique(values)Return unique values based on a hash table.
pandas.wide_to_long(df, stubnames, i, j, sep, suffix)Unpivot a DataFrame from wide to long format.
pandas.ArrowDtype(pyarrow_dtype)An ExtensionDtype for PyArrow data types.
pandas.BooleanDtype()Extension dtype for boolean data.
pandas.Categorical(values, categories, ordered, dtype, copy)Represent a categorical variable in classic R / S-plus fashion.
pandas.CategoricalDtype(categories, ordered)Type for categorical data with the categories and orderedness.
pandas.DataFrame(data, index, columns, dtype, copy)Two-dimensional, size-mutable, potentially heterogeneous tabular data.
pandas.DatetimeTZDtype(unit, tz)An ExtensionDtype for timezone-aware datetime data.
pandas.ExcelFile(path_or_buffer, engine, storage_options, engine_kwargs)Class for parsing tabular Excel sheets into DataFrame objects.
pandas.ExcelWriter(path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs)Class for writing DataFrame objects into excel sheets.
pandas.Flags(obj, allows_duplicate_labels)Flags that apply to pandas objects.
pandas.Float32Dtype()
pandas.Float64Dtype()
pandas.Grouper(key, level, freq, sort, dropna)A Grouper allows the user to specify a groupby instruction for an object.
pandas.HDFStore(path, mode, complevel, complib, fletcher32)Dict-like IO interface for storing pandas objects in PyTables.
pandas.Int16Dtype()
pandas.Int32Dtype()
pandas.Int64Dtype()
pandas.Int8Dtype()
pandas.IntervalDtype(subtype, closed)An ExtensionDtype for Interval data.
pandas.NamedAgg(column, aggfunc)Helper for column specific aggregation with control over output column names.
pandas.PeriodDtype()An ExtensionDtype for Period data.
pandas.Series(data, index, dtype, name, copy)One-dimensional ndarray with axis labels (including time series).
pandas.SparseDtype(dtype, fill_value)Dtype for data stored in SparseArray.
pandas.StringDtype(storage, na_value)Extension dtype for string data.
pandas.UInt16Dtype()
pandas.UInt32Dtype()
pandas.UInt64Dtype()
pandas.UInt8Dtype()
df.abs()Return a Series/DataFrame with absolute numeric value of each element.
df.add(other, axis, level, fill_value)Get Addition of dataframe and other, element-wise (binary operator add).
df.add_prefix(prefix, axis)Prefix labels with string prefix.
df.add_suffix(suffix, axis)Suffix labels with string suffix.
df.aggregate(func, axis)Aggregate using one or more operations over the specified axis.
df.align(other, join, axis, level, copy, fill_value)Align two objects on their axes with the specified join method.
df.all(axis, bool_only, skipna)Return whether all elements are True, potentially over an axis.
df.any(axis, bool_only, skipna)Return whether any element is True, potentially over an axis.
df.apply(func, axis, raw, result_type, args, by_row, engine, engine_kwargs)Apply a function along an axis of the DataFrame.
df.asfreq(freq, method, how, normalize, fill_value)Convert time series to specified frequency.
df.asof(where, subset)Return the last row(s) without any NaNs before where.
df.assign()Assign new columns to a DataFrame.
df.astype(dtype, copy, errors)Cast a pandas object to a specified dtype dtype.
df.at_time(time, asof, axis)Select values at particular time of day (e.g., 9:30AM).
df.between_time(start_time, end_time, inclusive, axis)Select values between particular times of the day (e.g., 9:00-9:30 AM).
df.bfill(axis, inplace, limit, limit_area)Fill NA/NaN values by using the next valid observation to fill the gap.
df.clip(lower, upper, axis, inplace)Trim values at input threshold(s).
df.combine(other, func, fill_value, overwrite)Perform column-wise combine with another DataFrame.
df.combine_first(other)Update null elements with value in the same location in other.
df.compare(other, align_axis, keep_shape, keep_equal, result_names)Compare to another DataFrame and show the differences.
df.convert_dtypes(infer_objects, convert_string, convert_integer, convert_boolean, convert_floating, dtype_backend)Convert columns from numpy dtypes to the best dtypes that support pd.NA.
df.copy(deep)Make a copy of this object's indices and data.
df.corr(method, min_periods, numeric_only)Compute pairwise correlation of columns, excluding NA/null values.
df.corrwith(other, axis, drop, method, numeric_only, min_periods)Compute pairwise correlation.
df.count(axis, numeric_only)Count non-NA cells for each column or row.
df.cov(min_periods, ddof, numeric_only)Compute pairwise covariance of columns, excluding NA/null values.
df.cummax(axis, skipna, numeric_only)Return cumulative maximum over a DataFrame or Series axis.
df.cummin(axis, skipna, numeric_only)Return cumulative minimum over a DataFrame or Series axis.
df.cumprod(axis, skipna, numeric_only)Return cumulative product over a DataFrame or Series axis.
df.cumsum(axis, skipna, numeric_only)Return cumulative sum over a DataFrame or Series axis.
df.describe(percentiles, include, exclude)Generate descriptive statistics.
df.diff(periods, axis)First discrete difference of element.
df.dot(other)Compute the matrix multiplication between the DataFrame and other.
df.drop(labels, axis, index, columns, level, inplace, errors)Drop specified labels from rows or columns.
df.drop_duplicates(subset, keep, inplace, ignore_index)Return DataFrame with duplicate rows removed.
df.droplevel(level, axis)Return Series/DataFrame with requested index / column level(s) removed.
df.dropna(axis, how, thresh, subset, inplace, ignore_index)Remove missing values.
df.duplicated(subset, keep)Return boolean Series denoting duplicate rows.
df.eq(other, axis, level)Get Equal to of dataframe and other, element-wise (binary operator eq).
df.equals(other)Test whether two objects contain the same elements.
df.eval(expr, inplace)Evaluate a string describing operations on DataFrame columns.
df.ewm(com, span, halflife, alpha, min_periods, adjust, ignore_na, times, method)Provide exponentially weighted (EW) calculations.
df.expanding(min_periods, method)Provide expanding window calculations.
df.explode(column, ignore_index)Transform each element of a list-like to a row, replicating index values.
df.ffill(axis, inplace, limit, limit_area)Fill NA/NaN values by propagating the last valid observation to next valid.
df.fillna(value, axis, inplace, limit)Fill NA/NaN values with value.
df.filter(arg, like, regex, axis, items, cond, na)Subset the rows or columns according to a boolean mask or the labels.
df.first_valid_index()Return index for first non-missing value or None, if no value is found.
df.floordiv(other, axis, level, fill_value)Get Integer division of dataframe and other, \ element-wise (binary operator floordiv).
df.from_arrow(data)Construct a DataFrame from a tabular Arrow object.
df.from_dict(data, orient, dtype, columns)Construct DataFrame from dict of array-like or dicts.
df.from_records(data, index, exclude, columns, coerce_float, nrows)Convert structured or record ndarray to DataFrame.
df.ge(other, axis, level)Get Greater than or equal to of dataframe and other, \ element-wise (binary operator ge).
df.get(key, default)Get item from object for given key (ex: DataFrame column).
df.groupby(by, level, as_index, sort, group_keys, observed, dropna)Group DataFrame using a mapper or by a Series of columns.
df.gt(other, axis, level)Get Greater than of dataframe and other, element-wise (binary operator gt).
df.head(n)Return the first n rows.
df.idxmax(axis, skipna, numeric_only)Return index of first occurrence of maximum over requested axis.
df.idxmin(axis, skipna, numeric_only)Return index of first occurrence of minimum over requested axis.
df.infer_objects(copy)Attempt to infer better dtypes for object columns.
df.info(verbose, buf, max_cols, memory_usage, show_counts)Print a concise summary of a DataFrame.
df.insert(loc, column, value, allow_duplicates)Insert column into DataFrame at specified location.
df.interpolate(method, axis, limit, inplace, limit_direction, limit_area)Fill NaN values using an interpolation method.
df.isetitem(loc, value)Set the given value in the column with position loc.
df.isin(values)Whether each element in the DataFrame is contained in values.
df.isna()Detect missing values.
df.isnull()DataFrame.isnull is an alias for DataFrame.isna.
df.items()Iterate over (column name, Series) pairs.
df.iterrows()Iterate over DataFrame rows as (index, Series) pairs.
df.itertuples(index, name)Iterate over DataFrame rows as namedtuples.
df.join(other, on, how, lsuffix, rsuffix, sort, validate, suffixes)Join columns of another DataFrame.
df.keys()Get the 'info axis' (see Indexing for more).
df.kurt(axis, skipna, numeric_only)Return unbiased kurtosis over requested axis.
df.last_valid_index()Return index for last non-missing value or None, if no value is found.
df.le(other, axis, level)Get Less than or equal to of dataframe and other, \ element-wise (binary operator le).
df.lt(other, axis, level)Get Less than of dataframe and other, element-wise (binary operator lt).
df.map(func, na_action)Apply a function to a Dataframe elementwise.
df.mask(cond, other, inplace, axis, level)Replace values where the condition is True.
df.max(axis, skipna, numeric_only)Return the maximum of the values over the requested axis.
df.mean(axis, skipna, numeric_only)Return the mean of the values over the requested axis.
df.median(axis, skipna, numeric_only)Return the median of the values over the requested axis.
df.melt(id_vars, value_vars, var_name, value_name, col_level, ignore_index)Unpivot DataFrame from wide to long format, optionally leaving identifiers set.
df.memory_usage(index, deep)Return the memory usage of each column in bytes.
df.merge(right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)Merge DataFrame or named Series objects with a database-style join.
df.min(axis, skipna, numeric_only)Return the minimum of the values over the requested axis.
df.mod(other, axis, level, fill_value)Get Modulo of dataframe and other, element-wise (binary operator mod).
df.mode(axis, numeric_only, dropna)Get the mode(s) of each element along the selected axis.
df.mul(other, axis, level, fill_value)Get Multiplication of dataframe and other, \ element-wise (binary operator mul).
df.ne(other, axis, level)Get Not equal to of dataframe and other, element-wise (binary operator ne).
df.nlargest(n, columns, keep)Return the first n rows ordered by columns in descending order.
df.notna()Detect existing (non-missing) values.
df.notnull()DataFrame.notnull is an alias for DataFrame.notna.
df.nsmallest(n, columns, keep)Return the first n rows ordered by columns in ascending order.
df.nunique(axis, dropna)Count number of distinct elements in specified axis.
df.pct_change(periods, fill_method, freq)Fractional change between the current and a prior element.
df.pipe(func)Apply chainable functions that expect Series or DataFrames.
df.pivot(columns, index, values)Return reshaped DataFrame organized by given index / column values.
df.pivot_table(values, index, columns, aggfunc, fill_value, margins, dropna, margins_name, observed, sort)Create a spreadsheet-style pivot table as a DataFrame.
df.pop(item)Return item and drop it from DataFrame.
df.pow(other, axis, level, fill_value)Get Exponential power of dataframe and other, \ element-wise (binary operator pow).
df.prod(axis, skipna, numeric_only, min_count)Return the product of the values over the requested axis.
df.quantile(q, axis, numeric_only, interpolation, method)Return values at the given quantile over requested axis.
df.query(expr, parser, engine, local_dict, global_dict, resolvers, level, inplace)Query the columns of a DataFrame with a boolean expression.
df.radd(other, axis, level, fill_value)Get Addition of dataframe and other, element-wise (binary operator radd).
df.rank(axis, method, numeric_only, na_option, ascending, pct)Compute numerical data ranks (1 through n) along axis.
df.reindex(labels, index, columns, axis, method, copy, level, fill_value, limit, tolerance)Conform DataFrame to new index with optional filling logic.
df.reindex_like(other, method, copy, limit, tolerance)Return an object with matching indices as other object.
df.rename(mapper, index, columns, axis, copy, inplace, level, errors)Rename columns or index labels.
df.rename_axis(mapper, index, columns, axis, copy, inplace)Set the name of the axis for the index or columns.
df.reorder_levels(order, axis)Rearrange index or column levels using input order.
df.replace(to_replace, value, inplace, regex)Replace values given in to_replace with value.
df.resample(rule, closed, label, convention, on, level, origin, offset, group_keys)Resample time-series data.
df.reset_index(level, drop, inplace, col_level, col_fill, allow_duplicates, names)Reset the index, or a level of it.
df.rfloordiv(other, axis, level, fill_value)Get Integer division of dataframe and other, \ element-wise (binary operator rfloordiv).
df.rmod(other, axis, level, fill_value)Get Modulo of dataframe and other, \ element-wise (binary operator rmod).
df.rmul(other, axis, level, fill_value)Get Multiplication of dataframe and other, \ element-wise (binary operator rmul).
df.rolling(window, min_periods, center, win_type, on, closed, step, method)Provide rolling window calculations.
df.round(decimals)Round numeric columns in a DataFrame to a variable number of decimal places.
df.rpow(other, axis, level, fill_value)Get Exponential power of dataframe and other, \ element-wise (binary operator rpow).
df.rsub(other, axis, level, fill_value)Get Subtraction of dataframe and other, element-wise (binary operator rsub).
df.rtruediv(other, axis, level, fill_value)Get Floating division of dataframe and other, \ element-wise (binary operator rtruediv).
df.sample(n, frac, replace, weights, random_state, axis, ignore_index)Return a random sample of items from an axis of object.
df.select()Select a subset of columns from the DataFrame.
df.select_dtypes(include, exclude)Return a subset of the DataFrame's columns based on the column dtypes.
df.sem(axis, skipna, ddof, numeric_only)Return unbiased standard error of the mean over requested axis.
df.set_axis(labels, axis, copy)Assign desired index to given axis.
df.set_flags(copy, allows_duplicate_labels)Return a new object with updated flags.
df.set_index(keys, drop, append, inplace, verify_integrity)Set the DataFrame index using existing columns.
df.shift(periods, freq, axis, fill_value, suffix)Shift index by desired number of periods with an optional time freq.
df.skew(axis, skipna, numeric_only)Return unbiased skew over requested axis.
df.sort_index(axis, level, ascending, inplace, kind, na_position, sort_remaining, ignore_index, key)Sort object by labels (along an axis).
df.sort_values(by, axis, ascending, inplace, kind, na_position, ignore_index, key)Sort by the values along either axis.
df.squeeze(axis)Squeeze 1 dimensional axis objects into scalars.
df.stack(level, dropna, sort, future_stack)Stack the prescribed level(s) from columns to index.
df.std(axis, skipna, ddof, numeric_only)Return sample standard deviation over requested axis.
df.sub(other, axis, level, fill_value)Get Subtraction of dataframe and other, element-wise (binary operator sub).
df.sum(axis, skipna, numeric_only, min_count)Return the sum of the values over the requested axis.
df.swaplevel(i, j, axis)Swap levels i and j in a MultiIndex.
df.tail(n)Return the last n rows.
df.take(indices, axis)Return the elements in the given positional indices along an axis.
df.to_clipboard(excel, sep)Copy object to the system clipboard.
df.to_csv(path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, lineterminator, chunksize, date_format, doublequote, escapechar, decimal, errors, storage_options)Write object to a comma-separated values (csv) file.
df.to_dict(orient, into)Convert the DataFrame to a dictionary.
df.to_excel(excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, inf_rep, freeze_panes, storage_options, engine_kwargs, autofilter)Write object to an Excel sheet.
df.to_feather(path)Write a DataFrame to the binary Feather format.
df.to_hdf(path_or_buf, key, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)Write the contained data to an HDF5 file using HDFStore.
df.to_html(buf, columns, col_space, header, index, na_rep, formatters, float_format, sparsify, index_names, justify, max_rows, max_cols, show_dimensions, decimal, bold_rows, classes, escape, notebook, border, table_id, render_links, encoding)Render a DataFrame as an HTML table.
df.to_iceberg(table_identifier, catalog_name, catalog_properties, location, append, snapshot_properties)Write a DataFrame to an Apache Iceberg table.
df.to_json(path_or_buf, orient, date_format, double_precision, force_ascii, date_unit, default_handler, lines, compression, index, indent, storage_options, mode)Convert the object to a JSON string.
df.to_latex(buf, columns, header, index, na_rep, formatters, float_format, sparsify, index_names, bold_rows, column_format, longtable, escape, encoding, decimal, multicolumn, multicolumn_format, multirow, caption, label, position)Render object to a LaTeX tabular, longtable, or nested table.
df.to_markdown(buf, mode, index, storage_options)Print DataFrame in Markdown-friendly format.
df.to_numpy(dtype, copy, na_value)Convert the DataFrame to a NumPy array.
df.to_orc(path, engine, index, engine_kwargs)Write a DataFrame to the Optimized Row Columnar (ORC) format.
df.to_parquet(path, engine, compression, index, partition_cols, storage_options, filesystem)Write a DataFrame to the binary parquet format.
df.to_period(freq, axis, copy)Convert DataFrame from DatetimeIndex to PeriodIndex.
df.to_pickle(path, compression, protocol, storage_options)Pickle (serialize) object to file.
df.to_records(index, column_dtypes, index_dtypes)Convert DataFrame to a NumPy record array.
df.to_sql(name, con, schema, if_exists, index, index_label, chunksize, dtype, method)Write records stored in a DataFrame to a SQL database.
df.to_stata(path, convert_dates, write_index, byteorder, time_stamp, data_label, variable_labels, version, convert_strl, compression, storage_options, value_labels)Export DataFrame object to Stata dta format.
df.to_string(buf, columns, col_space, header, index, na_rep, formatters, float_format, sparsify, index_names, justify, max_rows, max_cols, show_dimensions, decimal, line_width, min_rows, max_colwidth, encoding)Render a DataFrame to a console-friendly tabular output.
df.to_timestamp(freq, how, axis, copy)Cast PeriodIndex to DatetimeIndex of timestamps, at beginning of period.
df.to_xarray()Return an xarray object from the pandas object.
df.to_xml(path_or_buffer, index, root_name, row_name, na_rep, attr_cols, elem_cols, namespaces, prefix, encoding, xml_declaration, pretty_print, parser, stylesheet, compression, storage_options)Render a DataFrame to an XML document.
df.transform(func, axis)Call func on self producing a DataFrame with the same axis shape as self.
df.transpose(copy)Transpose index and columns.
df.truediv(other, axis, level, fill_value)Get Floating division of dataframe and other, \ element-wise (binary operator truediv).
df.truncate(before, after, axis, copy)Truncate a Series or DataFrame before and after some index value.
df.tz_convert(tz, axis, level, copy)Convert tz-aware axis to target time zone.
df.tz_localize(tz, axis, level, copy, ambiguous, nonexistent)Localize time zone naive index of a Series or DataFrame to target time zone.
df.unstack(level, fill_value, sort)Pivot a level of the (necessarily hierarchical) index labels.
df.update(other, join, overwrite, filter_func, errors)Modify in place using non-NA values from another DataFrame.
df.value_counts(subset, normalize, sort, ascending, dropna)Return a Series containing the frequency of each distinct row in the DataFrame.
df.var(axis, skipna, ddof, numeric_only)Return unbiased variance over requested axis.
df.where(cond, other, inplace, axis, level)Replace values where the condition is False.
df.xs(key, axis, level, drop_level)Return cross-section from the Series/DataFrame.
col.abs()Return a Series/DataFrame with absolute numeric value of each element.
col.add(other, level, fill_value, axis)Return Addition of series and other, element-wise (binary operator add).
col.add_prefix(prefix, axis)Prefix labels with string prefix.
col.add_suffix(suffix, axis)Suffix labels with string suffix.
col.aggregate(func, axis)Aggregate using one or more operations over the specified axis.
col.align(other, join, axis, level, copy, fill_value)Align two objects on their axes with the specified join method.
col.all(axis, bool_only, skipna)Return whether all elements are True, potentially over an axis.
col.any()Return whether any element is True, potentially over an axis.
col.apply(func, args, by_row)Invoke function on values of Series.
col.argmax(axis, skipna)Return int position of the largest value in the Series.
col.argmin(axis, skipna)Return int position of the smallest value in the Series.
col.argsort(axis, kind, order, stable)Return the integer indices that would sort the Series values.
col.asfreq(freq, method, how, normalize, fill_value)Convert time series to specified frequency.
col.asof(where, subset)Return the last row(s) without any NaNs before where.
col.astype(dtype, copy, errors)Cast a pandas object to a specified dtype dtype.
col.at_time(time, asof, axis)Select values at particular time of day (e.g., 9:30AM).
col.autocorr(lag)Compute the lag-N autocorrelation.
col.between(left, right, inclusive)Return boolean Series equivalent to left <= series <= right.
col.between_time(start_time, end_time, inclusive, axis)Select values between particular times of the day (e.g., 9:00-9:30 AM).
col.bfill(axis, inplace, limit, limit_area)Fill NA/NaN values by using the next valid observation to fill the gap.
col.case_when(caselist)Replace values where the conditions are True.
col.clip(lower, upper, axis, inplace)Trim values at input threshold(s).
col.combine(other, func, fill_value)Combine the Series with a Series or scalar according to func.
col.combine_first(other)Update null elements with value in the same location in 'other'.
col.compare(other, align_axis, keep_shape, keep_equal, result_names)Compare to another Series and show the differences.
col.convert_dtypes(infer_objects, convert_string, convert_integer, convert_boolean, convert_floating, dtype_backend)Convert columns from numpy dtypes to the best dtypes that support pd.NA.
col.copy(deep)Make a copy of this object's indices and data.
col.corr(other, method, min_periods)Compute correlation with other Series, excluding missing values.
col.count()Return number of non-NA/null observations in the Series.
col.cov(other, min_periods, ddof)Compute covariance with Series, excluding missing values.
col.cummax(axis, skipna)Return cumulative maximum over a Series.
col.cummin(axis, skipna)Return cumulative minimum over a Series.
col.cumprod(axis, skipna)Return cumulative product over a Series.
col.cumsum(axis, skipna)Return cumulative sum over a Series.
col.describe(percentiles, include, exclude)Generate descriptive statistics.
col.diff(periods)First discrete difference of Series elements.
col.divmod(other, level, fill_value, axis)Return Integer division and modulo of series and other, \ element-wise (binary operator divmod).
col.dot(other)Compute the dot product between the Series and the columns of other.
col.drop(labels, axis, index, columns, level, inplace, errors)Return Series with specified index labels removed.
col.drop_duplicates(keep, inplace, ignore_index)Return Series with duplicate values removed.
col.droplevel(level, axis)Return Series/DataFrame with requested index / column level(s) removed.
col.dropna(axis, inplace, how, ignore_index)Return a new Series with missing values removed.
col.duplicated(keep)Indicate duplicate Series values.
col.eq(other, level, fill_value, axis)Return Equal to of series and other, element-wise (binary operator eq).
col.equals(other)Test whether two objects contain the same elements.
col.ewm(com, span, halflife, alpha, min_periods, adjust, ignore_na, times, method)Provide exponentially weighted (EW) calculations.
col.expanding(min_periods, method)Provide expanding window calculations.
col.explode(ignore_index)Transform each element of a list-like to a row.
col.factorize(sort, use_na_sentinel)Encode the object as an enumerated type or categorical variable.
col.ffill(axis, inplace, limit, limit_area)Fill NA/NaN values by propagating the last valid observation to next valid.
col.fillna(value, axis, inplace, limit)Fill NA/NaN values with value.
col.filter(arg, like, regex, axis, items, cond, na)Subset the rows or columns according to a boolean mask or the labels.
col.first_valid_index()Return index for first non-missing value or None, if no value is found.
col.floordiv(other, level, fill_value, axis)Return Integer division of series and other, \ element-wise (binary operator floordiv).
col.from_arrow(data)Construct a Series from an array-like Arrow object.
col.ge(other, level, fill_value, axis)Return Greater than or equal to of series and other, \ element-wise (binary operator ge).
col.get(key, default)Get item from object for given key (ex: DataFrame column).
col.groupby(by, level, as_index, sort, group_keys, observed, dropna)Group Series using a mapper or by a Series of columns.
col.gt(other, level, fill_value, axis)Return Greater than of series and other, element-wise (binary operator gt).
col.head(n)Return the first n rows.
col.idxmax(axis, skipna)Return the row label of the maximum value.
col.idxmin(axis, skipna)Return the row label of the minimum value.
col.infer_objects(copy)Attempt to infer better dtypes for object columns.
col.info(verbose, buf, max_cols, memory_usage, show_counts)Print a concise summary of a Series.
col.interpolate(method, axis, limit, inplace, limit_direction, limit_area)Fill NaN values using an interpolation method.
col.isin(values)Whether elements in Series are contained in values.
col.isna()Detect missing values.
col.isnull()Series.isnull is an alias for Series.isna.
col.item()Return the first element of the underlying data as a Python scalar.
col.items()Lazily iterate over (index, value) tuples.
col.keys()Return alias for index.
col.kurt(axis, skipna, numeric_only)Return unbiased kurtosis over requested axis.
col.last_valid_index()Return index for last non-missing value or None, if no value is found.
col.le(other, level, fill_value, axis)Return Less than or equal to of series and other, \ element-wise (binary operator le).
col.lt(other, level, fill_value, axis)Return Less than of series and other, element-wise (binary operator lt).
col.map(func, na_action, engine)Map values of Series according to an input mapping or function.
col.mask(cond, other, inplace, axis, level)Replace values where the condition is True.
col.max(axis, skipna, numeric_only)Return the maximum of the values over the requested axis.
col.mean(axis, skipna, numeric_only)Return the mean of the values over the requested axis.
col.median(axis, skipna, numeric_only)Return the median of the values over the requested axis.
col.memory_usage(index, deep)Return the memory usage of the Series.
col.min(axis, skipna, numeric_only)Return the minimum of the values over the requested axis.
col.mod(other, level, fill_value, axis)Return Modulo of series and other, element-wise (binary operator mod).
col.mode(dropna)Return the mode(s) of the Series.
col.mul(other, level, fill_value, axis)Return Multiplication of series and other, element-wise (binary operator mul).
col.ne(other, level, fill_value, axis)Return Not equal to of series and other, element-wise (binary operator ne).
col.nlargest(n, keep)Return the largest n elements.
col.notna()Detect existing (non-missing) values.
col.notnull()Series.notnull is an alias for Series.notna.
col.nsmallest(n, keep)Return the smallest n elements.
col.nunique(dropna)Return number of unique elements in the object.
col.pct_change(periods, fill_method, freq)Fractional change between the current and a prior element.
col.pipe(func)Apply chainable functions that expect Series or DataFrames.
col.pop(item)Return item and drops from series.
col.pow(other, level, fill_value, axis)Return Exponential power of series and other, \ element-wise (binary operator pow).
col.prod(axis, skipna, numeric_only, min_count)Return the product of the values over the requested axis.
col.quantile(q, interpolation)Return value at the given quantile.
col.radd(other, level, fill_value, axis)Return Addition of series and other, element-wise (binary operator radd).
col.rank(axis, method, numeric_only, na_option, ascending, pct)Compute numerical data ranks (1 through n) along axis.
col.rdivmod(other, level, fill_value, axis)Return Integer division and modulo of series and other, \ element-wise (binary operator rdivmod).
col.reindex()Conform Series to new index with optional filling logic.
col.reindex_like(other, method, copy, limit, tolerance)Return an object with matching indices as other object.
col.rename(index, axis, copy, inplace, level, errors)Alter Series index labels or name.
col.rename_axis(mapper, index, axis, copy, inplace)Set the name of the axis for the index.
col.reorder_levels(order)Rearrange index levels using input order.
col.repeat(repeats, axis)Repeat elements of a Series.
col.replace(to_replace, value, inplace, regex)Replace values given in to_replace with value.
col.resample(rule, closed, label, convention, on, level, origin, offset, group_keys)Resample time-series data.
col.reset_index(level, drop, name, inplace, allow_duplicates)Generate a new DataFrame or Series with the index reset.
col.rfloordiv(other, level, fill_value, axis)Return Integer division of series and other, \ element-wise (binary operator rfloordiv).
col.rmod(other, level, fill_value, axis)Return Modulo of series and other, \ element-wise (binary operator rmod).
col.rmul(other, level, fill_value, axis)Return Multiplication of series and other, \ element-wise (binary operator rmul).
col.rolling(window, min_periods, center, win_type, on, closed, step, method)Provide rolling window calculations.
col.round(decimals)Round each value in a Series to the given number of decimals.
col.rpow(other, level, fill_value, axis)Return Exponential power of series and other, \ element-wise (binary operator rpow).
col.rsub(other, level, fill_value, axis)Return Subtraction of series and other, element-wise (binary operator rsub).
col.rtruediv(other, level, fill_value, axis)Return Floating division of series and other, \ element-wise (binary operator rtruediv).
col.sample(n, frac, replace, weights, random_state, axis, ignore_index)Return a random sample of items from an axis of object.
col.searchsorted()Find indices where elements should be inserted to maintain order.
col.sem(axis, skipna, ddof, numeric_only)Return unbiased standard error of the mean over requested axis.
col.set_axis(labels, axis, copy)Assign desired index to given axis.
col.set_flags(copy, allows_duplicate_labels)Return a new object with updated flags.
col.shift(periods, freq, axis, fill_value, suffix)Shift index by desired number of periods with an optional time freq.
col.skew(axis, skipna, numeric_only)Return unbiased skew over requested axis.
col.sort_index(axis, level, ascending, inplace, kind, na_position, sort_remaining, ignore_index, key)Sort Series by index labels.
col.sort_values(axis, ascending, inplace, kind, na_position, ignore_index, key)Sort by the values.
col.squeeze(axis)Squeeze 1 dimensional axis objects into scalars.
col.std(axis, skipna, ddof, numeric_only)Return sample standard deviation.
col.sub(other, level, fill_value, axis)Return Subtraction of series and other, element-wise (binary operator sub).
col.sum(axis, skipna, numeric_only, min_count)Return the sum of the values over the requested axis.
col.swaplevel(i, j, copy)Swap levels i and j in a MultiIndex.
col.tail(n)Return the last n rows.
col.take(indices, axis)Return the elements in the given positional indices along an axis.
col.to_clipboard(excel, sep)Copy object to the system clipboard.
col.to_csv(path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, lineterminator, chunksize, date_format, doublequote, escapechar, decimal, errors, storage_options)Write object to a comma-separated values (csv) file.
col.to_dict(into)Convert Series to {label -> value} dict or dict-like object.
col.to_excel(excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, inf_rep, freeze_panes, storage_options, engine_kwargs, autofilter)Write object to an Excel sheet.
col.to_frame(name)Convert Series to DataFrame.
col.to_hdf(path_or_buf, key, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)Write the contained data to an HDF5 file using HDFStore.
col.to_json(path_or_buf, orient, date_format, double_precision, force_ascii, date_unit, default_handler, lines, compression, index, indent, storage_options, mode)Convert the object to a JSON string.
col.to_latex(buf, columns, header, index, na_rep, formatters, float_format, sparsify, index_names, bold_rows, column_format, longtable, escape, encoding, decimal, multicolumn, multicolumn_format, multirow, caption, label, position)Render object to a LaTeX tabular, longtable, or nested table.
col.to_markdown(buf, mode, index, storage_options)Print Series in Markdown-friendly format.
col.to_numpy(dtype, copy, na_value)A NumPy ndarray representing the values in this Series or Index.
col.to_period(freq, copy)Convert Series from DatetimeIndex to PeriodIndex.
col.to_pickle(path, compression, protocol, storage_options)Pickle (serialize) object to file.
col.to_sql(name, con, schema, if_exists, index, index_label, chunksize, dtype, method)Write records stored in a DataFrame to a SQL database.
col.to_string(buf, na_rep, float_format, header, index, length, dtype, name, max_rows, min_rows)Render a string representation of the Series.
col.to_timestamp(freq, how, copy)Cast to DatetimeIndex of Timestamps, at beginning of period.
col.to_xarray()Return an xarray object from the pandas object.
col.tolist()Return a list of the values.
col.transform(func, axis)Call func on self producing a Series with the same axis shape as self.
col.transpose()Return the transpose, which is by definition self.
col.truediv(other, level, fill_value, axis)Return Floating division of series and other, \ element-wise (binary operator truediv).
col.truncate(before, after, axis, copy)Truncate a Series or DataFrame before and after some index value.
col.tz_convert(tz, axis, level, copy)Convert tz-aware axis to target time zone.
col.tz_localize(tz, axis, level, copy, ambiguous, nonexistent)Localize time zone naive index of a Series or DataFrame to target time zone.
col.unique()Return unique values of Series object.
col.unstack(level, fill_value, sort)Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
col.update(other)Modify Series in place using values from passed Series.
col.value_counts(normalize, sort, ascending, bins, dropna)Return a Series containing counts of unique values.
col.var(axis, skipna, ddof, numeric_only)Return unbiased variance over requested axis.
col.where(cond, other, inplace, axis, level)Replace values where the condition is False.
col.xs(key, axis, level, drop_level)Return cross-section from the Series/DataFrame.
openpyxl 3.1.5 36
CommandWhat it does
openpyxl.load_workbook(filename, read_only, keep_vba, data_only, keep_links, rich_text)Open the given filename and return the workbook
openpyxl.open(filename, read_only, keep_vba, data_only, keep_links, rich_text)Open the given filename and return the workbook
openpyxl.Workbook(write_only, iso_dates)Workbook is the container for all other parts of the document.
wb.add_named_style(style)Add a named style
wb.close()Close workbook file if open.
wb.copy_worksheet(from_worksheet)Copy an existing worksheet in the current workbook
wb.create_chartsheet(title, index)
wb.create_named_range(name, worksheet, value, scope)Create a new named_range on a worksheet
wb.create_sheet(title, index)Create a worksheet (at an optional index).
wb.get_index(worksheet)Return the index of the worksheet.
wb.get_sheet_by_name(name)Returns a worksheet by its name.
wb.get_sheet_names()
wb.index(worksheet)Return the index of a worksheet.
wb.move_sheet(sheet, offset)Move a sheet or sheetname
wb.remove(worksheet)Remove worksheet from this workbook.
wb.remove_sheet(worksheet)Remove worksheet from this workbook.
wb.save(filename)Save the current workbook under the given filename.
worksheet.Worksheet(parent, title)Represents a worksheet.
ws.add_chart(chart, anchor)Add a chart to the sheet Optionally provide a cell for the top-left anchor
ws.add_data_validation(data_validation)Add a data-validation object to the sheet.
ws.add_image(img, anchor)Add an image to the sheet.
ws.add_pivot(pivot)
ws.add_table(table)Check for duplicate name in definedNames and other worksheet tables before adding table.
ws.append(iterable)Appends a group of values at the bottom of the current sheet.
ws.calculate_dimension()Return the minimum bounding range for all cells containing data (ex.
ws.cell(row, column, value)Returns a cell object based on the given coordinates.
ws.delete_cols(idx, amount)Delete column or columns from col==idx
ws.delete_rows(idx, amount)Delete row or rows from row==idx
ws.insert_cols(idx, amount)Insert column or columns before col==idx
ws.insert_rows(idx, amount)Insert row or rows before row==idx
ws.iter_cols(min_col, max_col, min_row, max_row, values_only)Produces cells from the worksheet, by column.
ws.iter_rows(min_row, max_row, min_col, max_col, values_only)Produces cells from the worksheet, by row.
ws.merge_cells(range_string, start_row, start_column, end_row, end_column)Set merge on a cell range.
ws.move_range(cell_range, rows, cols, translate)Move a cell range by the number of rows and/or columns: down if rows > 0 and up if rows < 0 right if cols > 0 and left if cols < 0 Existing cells will be overwritten.
ws.set_printer_settings(paper_size, orientation)Set printer settings
ws.unmerge_cells(range_string, start_row, start_column, end_row, end_column)Remove merge on a cell range.
pillow 13.0.0 159
CommandWhat it does
Image.alpha_composite(im1, im2)Alpha composite im2 over im1.
Image.blend(im1, im2, alpha)Creates a new image by interpolating between two input images, using a constant alpha::
Image.composite(image1, image2, mask)Create composite image by blending images using a transparency mask.
Image.effect_mandelbrot(size, extent, quality)Generate a Mandelbrot set covering the given extent.
Image.effect_noise(size, sigma)Generate Gaussian noise centered around 128.
Image.eval(image)Applies the function (which should take one argument) to each pixel in the given image.
Image.fromarray(obj, mode)Creates an image memory from an object exporting the array interface (using the buffer protocol)::
Image.fromarrow(obj, mode, size)Creates an image with zero-copy shared memory from an object exporting the arrow_c_array interface protocol::
Image.frombuffer(mode, size, data, decoder_name)Creates an image memory referencing pixel data in a byte buffer.
Image.frombytes(mode, size, data, decoder_name)Creates a copy of an image memory from pixel data in a buffer.
Image.fromqimage(im)Creates an image instance from a QImage image
Image.fromqpixmap(im)Creates an image instance from a QPixmap image
Image.getmodebandnames(mode)Gets a list of individual band names.
Image.getmodebands(mode)Gets the number of individual bands for this mode.
Image.getmodebase(mode)Gets the "base" mode for given mode.
Image.getmodetype(mode)Gets the storage type mode.
Image.init()Explicitly initializes the Python Imaging Library.
Image.linear_gradient(mode)Generate 256x256 linear gradient from black to white, top to bottom.
Image.merge(mode, bands)Merge a set of single band images into a new multiband image.
Image.new(mode, size, color)Creates a new image with the given mode and size.
Image.open(fp, mode, formats)Opens and identifies the given image file.
Image.preinit()Explicitly loads BMP, GIF, JPEG, PPM and PNG file format drivers.
Image.radial_gradient(mode)Generate 256x256 radial gradient from black to white, centre to edge.
Image.registered_extensions()Returns a dictionary containing all file extensions belonging to registered plugins
Image.Dither()
Image.Exif()This class provides read and write access to EXIF image data::
Image.Image()This class represents an image object.
Image.ImagePointHandler()Used as a mixin by point transforms (for use with :py~PIL.Image.Image.point)
Image.ImagePointTransform(scale, offset)Used with :py~PIL.Image.Image.point for single band images with more than 8 bits, this represents an affine transformation, where the value is multiplied by scale and offset is added.
Image.ImageTransformHandler()Used as a mixin by geometry transforms (for use with :py~PIL.Image.Image.transform)
Image.Palette()
Image.Quantize()
Image.Resampling()
Image.SupportsArrayInterface()An object that has an __array_interface__ dictionary.
Image.SupportsArrowArrayInterface()An object that has an __arrow_c_array__ method corresponding to the arrow c data interface.
Image.SupportsGetData()
Image.Transform()
Image.Transpose()
img.alpha_composite(im, dest, source)'In-place' analog of Image.alpha_composite.
img.apply_transparency()If a P mode image has a "transparency" key in the info dictionary, remove the key and instead apply the transparency to the palette.
img.close()This operation will destroy the image core and release its memory.
img.convert(mode, matrix, dither, palette, colors)Returns a converted copy of this image.
img.copy()Copies this image.
img.crop(box)Returns a rectangular region from this image.
img.draft(mode, size)Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size.
img.effect_spread(distance)Randomly spread pixels in an image.
img.entropy(mask, extrema)Calculates and returns the entropy for the image.
img.filter(filter)Filters this image using the given filter.
img.frombytes(data, decoder_name)Loads this image with pixel data from a bytes object.
img.get_flattened_data(band)Returns the contents of this image as a tuple containing pixel values.
img.getbands()Returns a tuple containing the name of each band in this image.
img.getbbox(alpha_only)Calculates the bounding box of the non-zero regions in the image.
img.getchannel(channel)Returns an image containing a single channel of the source image.
img.getcolors(maxcolors)Returns a list of colors used in this image.
img.getdata(band)Returns the contents of this image as a sequence object containing pixel values.
img.getexif()Gets EXIF data from the image.
img.getextrema()Gets the minimum and maximum pixel values for each band in the image.
img.getim()Returns a capsule that points to the internal image memory.
img.getpalette(rawmode)Returns the image palette as a list.
img.getpixel(xy)Returns the pixel value at a given position.
img.getprojection()Get projection to x and y axes
img.getxmp(strip_namespaces)Returns a dictionary containing the XMP tags.
img.histogram(mask, extrema)Returns a histogram for the image.
img.load()Allocates storage for the image and loads the pixel data.
img.paste(im, box, mask)Pastes another image into this image.
img.point(lut, mode)Maps this image through a lookup table or function.
img.putalpha(alpha)Adds or replaces the alpha layer in this image.
img.putdata(data, scale, offset)Copies pixel data from a flattened sequence object into the image.
img.putpalette(data, rawmode)Attaches a palette to this image.
img.putpixel(xy, value)Modifies the pixel at the given position.
img.quantize(colors, method, kmeans, palette, dither)Convert the image to 'P' mode with the specified number of colors.
img.reduce(factor, box)Returns a copy of the image reduced factor times.
img.remap_palette(dest_map, source_palette)Rewrites the image to reorder the palette.
img.resize(size, resample, box, reducing_gap)Returns a resized copy of this image.
img.rotate(angle, resample, expand, center, translate, fillcolor)Returns a rotated copy of this image.
img.save(fp, format)Saves this image under the given filename.
img.seek(frame)Seeks to the given frame in this sequence file.
img.show(title)Displays this image.
img.split()Split this image into individual bands.
img.tell()Returns the current frame number.
img.thumbnail(size, resample, reducing_gap)Make this image into a thumbnail.
img.tobitmap(name)Returns the image converted to an X11 bitmap.
img.tobytes(encoder_name)Return image as a bytes object.
img.toqimage()Returns a QImage copy of this image
img.toqpixmap()Returns a QPixmap copy of this image
img.transform(size, method, data, resample, fill, fillcolor)Transforms this image.
img.transpose(method)Transpose image (flip or rotate in 90 degree steps)
img.verify()Verifies the contents of a file.
ImageOps.autocontrast(image, cutoff, ignore, mask, preserve_tone)Maximize (normalize) image contrast.
ImageOps.colorize(image, black, white, mid, blackpoint, whitepoint, midpoint)Colorize grayscale image.
ImageOps.contain(image, size, method)Returns a resized version of the image, set to the maximum width and height within the requested size, while maintaining the original aspect ratio.
ImageOps.cover(image, size, method)Returns a resized version of the image, so that the requested size is covered, while maintaining the original aspect ratio.
ImageOps.crop(image, border)Remove border from image.
ImageOps.deform(image, deformer, resample)Deform the image.
ImageOps.equalize(image, mask)Equalize the image histogram.
ImageOps.exif_transpose(image, in_place)If an image has an EXIF Orientation tag, other than 1, transpose the image accordingly, and remove the orientation data.
ImageOps.expand(image, border, fill)Add border to the image
ImageOps.fit(image, size, method, bleed, centering)Returns a resized and cropped version of the image, cropped to the requested aspect ratio and size.
ImageOps.flip(image)Flip the image vertically (top to bottom).
ImageOps.grayscale(image)Convert the image to grayscale.
ImageOps.invert(image)Invert (negate) the image.
ImageOps.mirror(image)Flip image horizontally (left to right).
ImageOps.pad(image, size, method, color, centering)Returns a resized and padded version of the image, expanded to fill the requested aspect ratio and size.
ImageOps.posterize(image, bits)Reduce the number of bits for each color channel.
ImageOps.scale(image, factor, resample)Returns a rescaled image by a specific factor given in parameter.
ImageOps.solarize(image, threshold)Invert all pixel values above a threshold.
ImageOps.SupportsGetMesh()An object that supports the getmesh method, taking an image as an argument, and returning a list of tuples.
ImageDraw.Draw(im, mode)A simple 2D drawing interface for PIL images.
ImageDraw.floodfill(image, xy, value, border, thresh)..
ImageDraw.getdraw(im):param im: The image to draw in.
ImageDraw.ImageDraw(im, mode)
draw.arc(xy, start, end, fill, width)Draw an arc.
draw.bitmap(xy, bitmap, fill)Draw a bitmap.
draw.chord(xy, start, end, fill, outline, width)Draw a chord.
draw.circle(xy, radius, fill, outline, width)Draw a circle given center coordinates and a radius.
draw.ellipse(xy, fill, outline, width)Draw an ellipse.
draw.getfont()Get the current default font.
draw.line(xy, fill, width, joint)Draw a line, or a connected sequence of line segments.
draw.multiline_text(xy, text, fill, font, anchor, spacing, align, direction, features, language, stroke_width, stroke_fill, embedded_color, font_size)
draw.multiline_textbbox(xy, text, font, anchor, spacing, align, direction, features, language, stroke_width, embedded_color, font_size)
draw.pieslice(xy, start, end, fill, outline, width)Draw a pieslice.
draw.point(xy, fill)Draw one or more individual pixels.
draw.polygon(xy, fill, outline, width)Draw a polygon.
draw.rectangle(xy, fill, outline, width)Draw a rectangle.
draw.regular_polygon(bounding_circle, n_sides, rotation, fill, outline, width)Draw a regular polygon.
draw.rounded_rectangle(xy, radius, fill, outline, width, corners)Draw a rounded rectangle.
draw.shape(shape, fill, outline)(Experimental) Draw a shape.
draw.text(xy, text, fill, font, anchor, spacing, align, direction, features, language, stroke_width, stroke_fill, embedded_color)Draw text.
draw.textbbox(xy, text, font, anchor, spacing, align, direction, features, language, stroke_width, embedded_color, font_size)Get the bounding box of a given string, in pixels.
draw.textlength(text, font, direction, features, language, embedded_color, font_size)Get the length of a given string, in pixels with 1/64 precision.
ImageFilter.BLUR()
ImageFilter.BoxBlur(radius)Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction.
ImageFilter.BuiltinFilter()
ImageFilter.Color3DLUT(size, table, channels, target_mode)Three-dimensional color lookup table.
ImageFilter.CONTOUR()
ImageFilter.DETAIL()
ImageFilter.EDGE_ENHANCE()
ImageFilter.EDGE_ENHANCE_MORE()
ImageFilter.EMBOSS()
ImageFilter.Filter()
ImageFilter.FIND_EDGES()
ImageFilter.GaussianBlur(radius)Blurs the image with a sequence of extended box filters, which approximates a Gaussian kernel.
ImageFilter.Kernel(size, kernel, scale, offset)Create a convolution kernel.
ImageFilter.MaxFilter(size)Create a max filter.
ImageFilter.MedianFilter(size)Create a median filter.
ImageFilter.MinFilter(size)Create a min filter.
ImageFilter.ModeFilter(size)Create a mode filter.
ImageFilter.MultibandFilter()
ImageFilter.RankFilter(size, rank)Create a rank filter.
ImageFilter.SHARPEN()
ImageFilter.SMOOTH()
ImageFilter.SMOOTH_MORE()
ImageFilter.UnsharpMask(radius, percent, threshold)Unsharp mask filter.
ImageGrab.grab(bbox, include_layered_windows, all_screens, xdisplay, window, scale_down)
ImageGrab.grabclipboard()
ImageEnhance.Brightness(image)Adjust image brightness.
ImageEnhance.Color(image)Adjust image color balance.
ImageEnhance.Contrast(image)Adjust image contrast.
ImageEnhance.Sharpness(image)Adjust image sharpness.
pypdf 7.1.1 121
CommandWhat it does
pypdf.apply_configuration(configuration)Temporarily overwrite the configuration.
pypdf.get_configuration()Get the current configuration.
pypdf.mult(m, n)
pypdf.overwrite_configuration(configuration)Overwrite the configuration for the current execution context.
pypdf.parse_filename_page_ranges(args)Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
pypdf.Configuration()Configuration used while processing PDF files.
pypdf.DocumentInformation()A class representing the basic document metadata provided in a PDF File.
pypdf.ImageType()
pypdf.ObjectDeletionFlag()
pypdf.PageObject(pdf, indirect_reference)PageObject represents a single page within a PDF file.
pypdf.PageRange(arg)A slice-like representation of a range of page indices.
pypdf.PaperSize()(width, height) of the paper in portrait mode in pixels at 72 ppi.
pypdf.PasswordType()
pypdf.PdfReader(stream, strict, password, root_object_recovery_limit, xref_stream_maximum_entries)Initialize a PdfReader object.
pypdf.PdfWriter(fileobj, clone_from, incremental, full, strict, keep_initial_header, incremental_clone_object_count_limit, incremental_clone_object_id_limit)Write a PDF file out, given pages produced by another class or through cloning a PDF file during initialization.
pypdf.Transformation(ctm)Represent a 2D transformation.
page.add_action(trigger, action)Add an action which will launch on the given trigger event of this page.
page.add_transformation(ctm, expand)Apply a transformation matrix to the page.
page.clone(pdf_dest, force_duplicate, ignore_fields)Clone object into pdf_dest.
page.compress_content_streams(level)Compress the size of this page by joining all content streams and applying a FlateDecode filter.
page.create_blank_page(pdf, width, height)Return a new blank page.
page.delete_action(trigger)Delete all actions associated with an open or close trigger event of this page.
page.extract_text(orientations, space_width, visitor_operand_before, visitor_operand_after, visitor_text, extraction_mode)Locate all text drawing commands, in the order they are provided in the content stream, and extract the text.
page.extract_xform_text(xform, orientations, space_width, visitor_operand_before, visitor_operand_after, visitor_text, known_ids, traversal_state)Extract text from an XObject.
page.get_contents()Access the page contents.
page.get_inherited(key, default)Returns the value of a key or from the parent if not found.
page.get_object()Resolve indirect references.
page.hash_bin()Used to detect modified object.
page.hash_value()
page.hash_value_data()
page.merge_page(page2, expand, over)Merge the content streams of two pages into one.
page.merge_rotated_page(page2, rotation, over, expand)Similar to ~pypdf._page.PageObject.merge_page, but the stream to be merged is rotated by applying a transformation matrix.
page.merge_scaled_page(page2, scale, over, expand)Similar to ~pypdf._page.PageObject.merge_page, but the stream to be merged is scaled by applying a transformation matrix.
page.merge_transformed_page(page2, ctm, over, expand)Similar to ~pypdf._page.PageObject.merge_page, but a transformation matrix is applied to the merged stream.
page.merge_translated_page(page2, tx, ty, over, expand)Similar to ~pypdf._page.PageObject.merge_page, but the stream to be merged is translated by applying a transformation matrix.
page.raw_get(key)
page.read_from_stream(stream, pdf, forced_encoding, parsing_budget)
page.replace_contents(content)Replace the page contents with the new content and nullify old objects Args: content: new content; if None delete the content field.
page.replicate(pdf_dest)
page.rotate(angle)Rotate a page clockwise by increments of 90 degrees.
page.scale(sx, sy)Scale a page by the given factors by applying a transformation matrix to its content and updating the page size.
page.scale_by(factor)Scale a page by the given factor by applying a transformation matrix to its content and updating the page size.
page.scale_to(width, height)Scale a page to the specified dimensions by applying a transformation matrix to its content and updating the page size.
page.setdefault(key, value)
page.transfer_rotation_to_content()Apply the rotation of the page to the content and the media/crop/...
page.write_to_stream(stream)
reader.add_form_topname(name)Add a top level form that groups all form fields below it.
reader.cache_get_indirect_object(generation, idnum)
reader.cache_indirect_object(generation, idnum, obj)
reader.close()Close the stream if opened in __init__ and clear memory.
reader.decrypt(password)When using an encrypted / secured PDF file with the PDF Standard encryption handler, this function will allow the file to be decrypted.
reader.get_destination_page_number(destination)Retrieve page number of a given Destination object.
reader.get_fields(tree, retval, fileobj, stack)Extract field data if this PDF contains interactive form fields.
reader.get_form_text_fields(full_qualified_name)Retrieve form fields from the document with textual data.
reader.get_named_dest_root()
reader.get_num_pages()Calculate the number of pages in this PDF file.
reader.get_object(indirect_reference)
reader.get_page(page_number)Retrieve a page by number from this PDF file.
reader.get_page_number(page)Retrieve page number of a given PageObject.
reader.get_pages_showing_field(field)Provides list of pages where the field is called.
reader.read(stream)Read and process the PDF stream, extracting necessary data.
reader.read_object_header(stream)
reader.remove_page(page, clean)Remove page from pages list.
reader.rename_form_topname(name)Rename top level form field that all form fields below it.
writer.add_annotation(page_number, annotation)Add a single annotation to the page.
writer.add_attachment(filename, data)Embed a file inside the PDF.
writer.add_blank_page(width, height)Append a blank page to this PDF file and return it.
writer.add_filtered_articles(fltr)Add articles matching the defined criteria.
writer.add_js(javascript)Add JavaScript which will launch upon opening this PDF.
writer.add_metadata(infos)Add custom metadata to the output.
writer.add_named_destination(title, page_number, fit)Add a named destination to a page in this PDF.
writer.add_named_destination_array(title, destination)
writer.add_named_destination_object(page_destination)
writer.add_open_action(action)Add an action to the document-level JavaScript name tree.
writer.add_outline()
writer.add_outline_item(title, page_number, parent, before, color, bold, italic, fit, is_open)Add an outline item (commonly referred to as a "Bookmark") to the PDF file.
writer.add_outline_item_destination(page_destination, parent, before, is_open)
writer.add_outline_item_dict(outline_item, parent, before, is_open)
writer.add_page(page, excluded_keys)Add a page to this PDF file.
writer.add_uri(page_number, uri, rect, border)Add an URI from a rectangular area to the specified page.
writer.append(fileobj, outline_item, pages, import_outline, excluded_fields)Identical to the merge()<merge> method, but assumes you want to concatenate all pages onto the end of the file instead of specifying a position.
writer.append_pages_from_reader(reader, after_page_append)Copy pages from reader to writer.
writer.clean_page(page)Perform some clean up in the page.
writer.clone_document_from_reader(reader, after_page_append)Create a copy (clone) of a document from a PDF file reader cloning section '/Root' and '/Info' and '/ID' of the pdf.
writer.clone_reader_document_root(reader)Copy the reader document root to the writer and all sub-elements, including pages, threads, outlines,...
writer.close()Implemented for API harmonization.
writer.compress_identical_objects(remove_identicals, remove_orphans, remove_duplicates, remove_unreferenced)Parse the PDF file and merge objects that have the same hash.
writer.create_viewer_preferences()
writer.encrypt(user_password, owner_password, use_128bit, permissions_flag, algorithm)Encrypt this PDF file with the PDF Standard encryption handler.
writer.find_outline_item(outline_item, root, visited)
writer.generate_file_identifiers()Generate an identifier for the PDF that will be written.
writer.get_destination_page_number(destination)Retrieve page number of a given Destination object.
writer.get_fields(tree, retval, fileobj, stack)Extract field data if this PDF contains interactive form fields.
writer.get_form_text_fields(full_qualified_name)Retrieve form fields from the document with textual data.
writer.get_named_dest_root()
writer.get_num_pages()Calculate the number of pages in this PDF file.
writer.get_object(indirect_reference)
writer.get_outline_root()
writer.get_page(page_number)Retrieve a page by number from this PDF file.
writer.get_page_number(page)Retrieve page number of a given PageObject.
writer.get_pages_showing_field(field)Provides list of pages where the field is called.
writer.get_reference(obj)
writer.get_threads_root()The list of threads.
writer.insert_blank_page(width, height, index)Insert a blank page to this PDF file and return it.
writer.insert_page(page, index, excluded_keys)Insert a page in this PDF file.
writer.list_objects_in_increment()For analysis or debugging.
writer.merge(position, fileobj, outline_item, pages, import_outline, excluded_fields)Merge the pages from the given file into the output file at the specified page number.
writer.reattach_fields(page)Parse annotations within the page looking for orphan fields and reattach then into the Fields Structure.
writer.remove_annotations(subtypes)Remove annotations by annotation subtype.
writer.remove_images(to_delete)Remove images from this output.
writer.remove_links()Remove links and annotations from this output.
writer.remove_objects_from_page(page, to_delete, text_filters)Remove objects specified by to_delete from the given page.
writer.remove_page(page, clean)Remove page from pages list.
writer.remove_text(font_names)Remove text from the PDF.
writer.reset_translation(reader)Reset the translation table between reader and the writer object.
writer.set_need_appearances_writer(state)Sets the "NeedAppearances" flag in the PDF writer.
writer.set_page_label(page_index_from, page_index_to, style, prefix, start)Set a page label to a range of pages.
writer.set_page_layout(layout)Set the page layout.
writer.update_page_form_field_values(page, fields, flags, auto_regenerate, flatten)Update the form field values for a given page from a fields dictionary.
writer.write(stream)Write the collection of pages added to this object out as a PDF file.
writer.write_stream(stream)
PyAutoGUI 0.9.54 37
CommandWhat it does
pyautogui.click(x, y, clicks, interval, button, duration, tween, logScreenshot)Performs pressing a mouse button down and then immediately releasing it.
pyautogui.countdown(seconds)
pyautogui.displayMousePosition(xOffset, yOffset)This function is meant to be run from the command line.
pyautogui.doubleClick(x, y, interval, button, duration, tween, logScreenshot)Performs a double click.
pyautogui.dragRel(xOffset, yOffset, duration, tween, button, logScreenshot, mouseDownUp)Performs a mouse drag (mouse movement while a button is held down) to a point on the screen, relative to its current position.
pyautogui.dragTo(x, y, duration, tween, button, logScreenshot, mouseDownUp)Performs a mouse drag (mouse movement while a button is held down) to a point on the screen.
pyautogui.failSafeCheck()
pyautogui.getInfo()
pyautogui.getPointOnLine(x1, y1, x2, y2, n)Returns an (x, y) tuple of the point that has progressed a proportion n along the line defined by the two x1, y1 and x2, y2 coordinates.
pyautogui.hold(keys, logScreenshot)Context manager that performs a keyboard key press down upon entry, followed by a release upon exit.
pyautogui.hotkey()Performs key down presses on the arguments passed in order, then performs key releases in reverse order.
pyautogui.hscroll(clicks, x, y, logScreenshot)Performs an explicitly horizontal scroll of the mouse scroll wheel, if this is supported by the operating system.
pyautogui.isShiftCharacter(character)Returns True if the character is a keyboard key that would require the shift key to be held down, such as uppercase letters or the symbols on the keyboard's number row.
pyautogui.isValidKey(key)Returns a Boolean value if the given key is a valid value to pass to PyAutoGUI's keyboard-related functions for the current platform.
pyautogui.keyDown(key, logScreenshot)Performs a keyboard key press without the release.
pyautogui.keyUp(key, logScreenshot)Performs a keyboard key release (without the press down beforehand).
pyautogui.leftClick(x, y, interval, duration, tween, logScreenshot)Performs a left mouse button click.
pyautogui.linear(n)Returns n, where n is the float argument between 0.0 and 1.0.
pyautogui.middleClick(x, y, interval, duration, tween, logScreenshot)Performs a middle mouse button click.
pyautogui.mouseDown(x, y, button, duration, tween, logScreenshot)Performs pressing a mouse button down (but not up).
pyautogui.mouseUp(x, y, button, duration, tween, logScreenshot)Performs releasing a mouse button up (but not down beforehand).
pyautogui.moveRel(xOffset, yOffset, duration, tween, logScreenshot)Moves the mouse cursor to a point on the screen, relative to its current position.
pyautogui.moveTo(x, y, duration, tween, logScreenshot)Moves the mouse cursor to a point on the screen.
pyautogui.onScreen(x, y)Returns whether the given xy coordinates are on the primary screen or not.
pyautogui.position(x, y)Returns the current xy coordinates of the mouse cursor as a two-integer tuple.
pyautogui.press(keys, presses, interval, logScreenshot)Performs a keyboard key press down, followed by a release.
pyautogui.printInfo(dontPrint)
pyautogui.raisePyAutoGUIImageNotFoundException(wrappedFunction)A decorator that wraps PyScreeze locate() functions so that the PyAutoGUI user sees them raise PyAutoGUI's ImageNotFoundException rather than PyScreeze's ImageNotFoundException.
pyautogui.rightClick(x, y, interval, duration, tween, logScreenshot)Performs a right mouse button click.
pyautogui.run(commandStr)Run a series of PyAutoGUI function calls according to a mini-language made for this function.
pyautogui.scroll(clicks, x, y, logScreenshot)Performs a scroll of the mouse scroll wheel.
pyautogui.size()Returns the width and height of the screen as a two-integer tuple.
pyautogui.sleep(seconds)
pyautogui.tripleClick(x, y, interval, button, duration, tween, logScreenshot)Performs a triple click.
pyautogui.typewrite(message, interval, logScreenshot)Performs a keyboard key press down, followed by a release, for each of the characters in message.
pyautogui.useImageNotFoundException(value)When called with no arguments, PyAutoGUI will raise ImageNotFoundException when the PyScreeze locate() functions can't find the image it was told to locate.
pyautogui.vscroll(clicks, x, y, logScreenshot)Performs an explicitly vertical scroll of the mouse scroll wheel, if this is supported by the operating system.
keyboard 0.13.5 43
CommandWhat it does
keyboard.add_abbreviation(source_text, replacement_text, match_suffix, timeout)Registers a hotkey that replaces one typed text with another.
keyboard.add_hotkey(hotkey, callback, args, suppress, timeout, trigger_on_release)Invokes a callback every time a hotkey is pressed.
keyboard.add_word_listener(word, callback, triggers, match_suffix, timeout)Invokes a callback every time a sequence of characters is typed (e.g.
keyboard.block_key(key)Suppresses all key events of the given key, regardless of modifiers.
keyboard.call_later(fn, args, delay)Calls the provided function in a new thread after waiting some time.
keyboard.get_hotkey_name(names)Returns a string representation of hotkey from the given key names, or the currently pressed keys if not given.
keyboard.get_typed_strings(events, allow_backspace)Given a sequence of events, tries to deduce what strings were typed.
keyboard.hook(callback, suppress, on_remove)Installs a global listener on all available keyboards, invoking callback each time a key is pressed or released.
keyboard.hook_key(key, callback, suppress)Hooks key up and key down events for a single key.
keyboard.is_modifier(key)Returns True if key is a scan code or name of a modifier key.
keyboard.is_pressed(hotkey)Returns True if the key is pressed.
keyboard.key_to_scan_codes(key, error_if_missing)Returns a list of scan codes associated with this key (name or scan code).
keyboard.normalize_name(name)Given a key name (e.g.
keyboard.on_press(callback, suppress)Invokes callback for every KEY_DOWN event.
keyboard.on_press_key(key, callback, suppress)Invokes callback for KEY_DOWN event related to the given key.
keyboard.on_release(callback, suppress)Invokes callback for every KEY_UP event.
keyboard.on_release_key(key, callback, suppress)Invokes callback for KEY_UP event related to the given key.
keyboard.parse_hotkey(hotkey)Parses a user-provided hotkey into nested tuples representing the parsed structure, with the bottom values being lists of scan codes.
keyboard.parse_hotkey_combinations(hotkey)Parses a user-provided hotkey.
keyboard.play(events, speed_factor)Plays a sequence of recorded events, maintaining the relative time intervals.
keyboard.press(hotkey)Presses and holds down a hotkey (see send).
keyboard.read_event(suppress)Blocks until a keyboard event happens, then returns that event.
keyboard.read_hotkey(suppress)Similar to read_key(), but blocks until the user presses and releases a hotkey (or single key), then returns a string representing the hotkey pressed.
keyboard.read_key(suppress)Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.
keyboard.record(until, suppress, trigger_on_release)Records all keyboard events from all keyboards until the user presses the given hotkey.
keyboard.release(hotkey)Releases a hotkey (see send).
keyboard.remap_hotkey(src, dst, suppress, trigger_on_release)Whenever the hotkey src is pressed, suppress it and send dst instead.
keyboard.remap_key(src, dst)Whenever the key src is pressed or released, regardless of modifiers, press or release the hotkey dst instead.
keyboard.remove_hotkey(hotkey_or_callback)Removes a previously hooked hotkey.
keyboard.remove_word_listener(word_or_handler)Removes a previously registered word listener.
keyboard.restore_modifiers(scan_codes)Like restore_state, but only restores modifier keys.
keyboard.restore_state(scan_codes)Given a list of scan_codes ensures these keys, and only these keys, are pressed.
keyboard.send(hotkey, do_press, do_release)Sends OS events that perform the given hotkey hotkey.
keyboard.start_recording(recorded_events_queue)Starts recording all keyboard events into a global variable, or the given queue if any.
keyboard.stash_state()Builds a list of all currently pressed scan codes, releases them and returns the list.
keyboard.stop_recording()Stops the global recording of events and returns a list of the events captured.
keyboard.unhook(remove)Removes a previously added hook, either by callback or by the return value of hook.
keyboard.unhook_all()Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, recorders and waits.
keyboard.unhook_all_hotkeys()Removes all keyboard hotkeys in use, including abbreviations, word listeners, recorders and waits.
keyboard.wait(hotkey, suppress, trigger_on_release)Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever.
keyboard.write(text, delay, restore_state_after, exact)Sends artificial keyboard events to the OS, simulating the typing of a given text.
keyboard.KeyboardEvent(event_type, scan_code, name, time, device, modifiers, is_keypad)
keyboardevent.to_json(ensure_ascii)
psutil 7.2.2 64
CommandWhat it does
psutil.AccessDenied()
psutil.boot_time()Return the system boot time expressed in seconds since the epoch (seconds since January 1, 1970, at midnight UTC).
psutil.cpu_count(logical)Return the number of logical CPUs in the system (same as os.cpu_count()).
psutil.cpu_freq()
psutil.cpu_percent(interval, percpu)Return a float representing the current system-wide CPU utilization as a percentage.
psutil.cpu_stats()Return CPU statistics.
psutil.cpu_times(percpu)Return system-wide CPU times as a namedtuple.
psutil.cpu_times_percent(interval, percpu)Same as cpu_percent() but provides utilization percentages for each specific CPU time as is returned by cpu_times().
psutil.disk_io_counters(perdisk, nowrap)Return system disk I/O statistics as a namedtuple including the following fields:
psutil.disk_partitions(all)Return mounted partitions as a list of (device, mountpoint, fstype, opts) namedtuple.
psutil.disk_usage(path)Return disk usage statistics about the given path as a namedtuple including total, used and free space expressed in bytes plus the percentage usage.
psutil.Error()
psutil.getloadavg()
psutil.net_connections(kind)Return system-wide socket connections as a list of (fd, family, type, laddr, raddr, status, pid) namedtuples.
psutil.net_if_addrs()Return the addresses associated to each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a list of namedtuples for each address assigned to the NIC.
psutil.net_if_stats()Return information about each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a namedtuple with the following fields:
psutil.net_io_counters(pernic, nowrap)Return network I/O statistics as a namedtuple including the following fields:
psutil.NoSuchProcess()
psutil.pid_exists(pid)Return True if given PID exists in the current process list.
psutil.pids()Return a list of current running PIDs.
psutil.process_iter(attrs, ad_value)Return a generator yielding a Process instance for all running processes.
psutil.sensors_battery()
psutil.sensors_fans()
psutil.sensors_temperatures()
psutil.swap_memory()Return system swap memory statistics as a namedtuple including the following fields:
psutil.TimeoutExpired()
psutil.users()Return users currently connected on the system as a list of namedtuples including the following fields.
psutil.version_info()
psutil.virtual_memory()Return statistics about system memory usage as a namedtuple including the following fields, expressed in bytes:
psutil.wait_procs(procs, timeout, callback)Convenience function which waits for a list of processes to terminate.
psutil.ZombieProcess()
psutil.Popen()Same as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class.
psutil.Process(pid)Represents an OS process with the given PID.
proc.as_dict(attrs, ad_value)Utility method returning process information as a hashable dictionary.
proc.children(recursive)Return the children of this process as a list of Process instances, pre-emptively checking whether PID has been reused.
proc.cmdline()The command line this process has been called with.
proc.connections(kind)
proc.cpu_percent(interval)Return a float representing the current process CPU utilization as a percentage.
proc.cpu_times()Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds.
proc.create_time()The process creation time as a floating point number expressed in seconds since the epoch (seconds since January 1, 1970, at midnight UTC).
proc.cwd()Process current working directory as an absolute path.
proc.exe()The process executable as an absolute path.
proc.is_running()Return whether this process is running.
proc.kill()Kill the current process with SIGKILL pre-emptively checking whether PID has been reused.
proc.memory_full_info()This method returns the same information as memory_info(), plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap).
proc.memory_info()Return a namedtuple with variable fields depending on the platform, representing memory information about the process.
proc.memory_percent(memtype)Compare process memory to total physical system memory and calculate process memory utilization as a percentage.
proc.name()The process name.
proc.net_connections(kind)Return socket connections opened by process as a list of (fd, family, type, laddr, raddr, status) namedtuples.
proc.nice(value)Get or set process niceness (priority).
proc.num_ctx_switches()Return the number of voluntary and involuntary context switches performed by this process.
proc.num_threads()Return the number of threads used by this process.
proc.oneshot()Utility context manager which considerably speeds up the retrieval of multiple process information at the same time.
proc.open_files()Return files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number.
proc.parent()Return the parent process as a Process object pre-emptively checking whether PID has been reused.
proc.parents()Return the parents of this process as a list of Process instances.
proc.ppid()The process parent PID.
proc.resume()Resume process execution with SIGCONT pre-emptively checking whether PID has been reused.
proc.send_signal(sig)Send a signal sig to process pre-emptively checking whether PID has been reused (see signal module constants) .
proc.status()The process current status as a STATUS_ constant.
proc.suspend()Suspend process execution with SIGSTOP pre-emptively checking whether PID has been reused.
proc.terminate()Terminate the process with SIGTERM pre-emptively checking whether PID has been reused.
proc.username()The name of the user that owns the process.
proc.wait(timeout)Wait for process to terminate, and if process is a children of os.getpid(), also return its exit code, else None.

Python Script Builder FAQ

Do I need to install Python?

Yes, to run the scripts. Get it from python.org and tick "Add python.exe to PATH" on the first screen of the installer. Building the script here needs nothing.

How do I run the .py file?

Double-click it, or open a terminal in its folder and type python my_script.py (py my_script.py works too on Windows). If it uses pip packages, run the Install & run .bat instead the first time, or run the pip install line shown above the code.

What is pip?

pip is the tool that installs extra packages for Python, like requests or pandas. It comes with Python. If Windows says pip isn't recognized, use py -m pip install followed by the package names, which works even when PATH wasn't set up.

Why does my text box turn into an f-string?

When you put a variable in curly brackets, like Hello {name}, the builder writes f"Hello {name}" so Python fills in the value. Without curly brackets it stays a normal "string". To print curly brackets themselves, type them twice, like {{this}}, and they come out as {this}. A lone { or } that isn't around a name prints as it is.

What's the difference between a text box and a value box?

Text boxes (like the message in "Show a message") are always text, so you type words and the quotes are added for you. Value boxes take Python as written: a number like 5, a variable like total, a list like ["a", "b"], or text in quotes like "yes".

Does it work on Mac and Linux?

Mostly. Python runs everywhere, and nearly every block works on all three. A few are Windows only and say so: opening files with their program, beeping, and shutting down. The Install & run .bat is for Windows; on Mac or Linux run the pip install line in a terminal instead.

Can it read any package?

Any package on PyPI that's written in Python, which is most of them. A few are almost all compiled code with very little Python inside, and those come back with few or no blocks. "Any line of code" can still use them.

Is my script uploaded anywhere?

No. The blocks and the code are built in your browser and saved only in this browser's storage. Adding a package from PyPI sends just its name to pypi.org to download it; nothing about your script goes with it.