print()
Shows something on the screen. Anything in quotes is text; anything without is worked out first.
print("Hello, Data Analytics")
print(2026)
print(60 * 7)
Shows something on the screen. Anything in quotes is text; anything without is worked out first.
print("Hello, Data Analytics")
print(2026)
print(60 * 7)
Separate the parts with commas. Python puts a single space between them for you.
name = "Rahul"
dept = "HR"
print("Employee", name, "works in", dept)
Anything after a # is ignored by Python. It is a note for the human reading the code.
# this line does nothing at all
salary = 47764 # monthly, in rupees
print(salary)
A name that holds a value. Assign with a single =, and you can change it later.
emp_id = 1001
name = "Rahul Sharma"
salary = 47764
print(emp_id, name, salary)
salary = 52000 # changed
print("after the hike:", salary)
name = "Anita"
city = "Chennai"
age = 22
print(name, "is", age, "and lives in", city)
Counting numbers, positive or negative, with no decimal point.
experience = 4
print(experience)
print(type(experience))
Any number with a dot in it. Division always produces one, even when it divides evenly.
height = 169.5
print(height, type(height))
print(10 / 2, type(10 / 2))
Anything inside quotes. Single or double quotes both work, as long as you match them.
dept = 'HR'
city = "Hyderabad"
print(dept, city)
print(type(dept))
Only two possible values, and both start with a capital letter.
is_active = True
print(is_active, type(is_active))
print(5 > 3)
print(5 == 3)
Asks Python what something is. Useful the moment a value does not behave the way you expected.
print(type(10))
print(type(10.0))
print(type("10"))
print(type(True))
for v in [7, 7.0, "7", True]:
print(v, "->", type(v))
Turns something into a whole number. On a float it CUTS the decimal off — it does not round.
print(int("25"))
print(int(9.99)) # 9, not 10
print(int(True))
float() adds a decimal point, str() turns a number into text so it can be joined to other text.
print(float(25), type(float(25)))
print(str(25) + " employees")
"25" and 25 look the same on screen and behave completely differently. Text repeats; numbers add.
print("25" + "25") # text joins
print(25 + 25) # numbers add
print(int("25") + 25) # convert first
int() only works on something that really is a number. Anything else stops the program.
print(int("50"))
print(int("fifty"))
salary = "47764"
total = int(salary) + int(salary) * 10 / 100
print(total)
Stops and waits for the user to type. Whatever they type arrives as TEXT, always.
name = input("Enter your name: ")
print("Welcome,", name)
print(type(name))
input() hands back text, so you must convert before doing any maths with it.
age = input("Enter your age: ")
print("next year you are", age + 1)
Wrap input() in int() — or float() if decimals are possible.
age = int(input("Enter your age: "))
print("next year you are", age + 1)
a = int(input("first number: "))
b = int(input("second number: "))
print("sum is", a + b)
The usual five, plus // for whole-number division and % for the remainder.
a, b = 17, 5
print("add ", a + b)
print("subtract ", a - b)
print("multiply ", a * b)
print("divide ", a / b) # always a float
print("floor ", a // b) # whole part only
print("remainder", a % b)
print("power ", a ** 2)
The remainder operator is how you check whether a number divides evenly. Remainder 0 means it does.
for n in [10, 7, 24]:
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
Six of them, and every one hands back True or False. Note == is a question, = is an instruction.
salary = 47764
print(salary > 50000)
print(salary < 50000)
print(salary == 47764)
print(salary != 47764)
print(salary >= 47764)
Join two conditions. and needs both true; or needs one; not flips it.
dept, salary = "Tech", 62990
print(dept == "Tech" and salary > 50000)
print(dept == "HR" or salary > 50000)
print(not dept == "Tech")
n = int(input("number: "))
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
dept, salary = "Tech", 48000
print(dept == "Tech" and salary > 50000)
Runs the indented block only when the condition is True. The colon and the indent are both required.
salary = 62990
if salary > 50000:
print("above fifty thousand")
print("this line always runs")
Two paths, and exactly one of them runs.
age = 17
if age >= 18:
print("can vote")
else:
print("cannot vote yet")
More than two paths. Python checks top to bottom and stops at the FIRST one that is true.
marks = 72
if marks >= 90:
print("A")
elif marks >= 75:
print("B")
elif marks >= 60:
print("C")
else:
print("D")
Because it stops at the first match, a loose condition placed first swallows all the rest.
marks = 95
# WRONG - 95 is >= 60, so it stops here
if marks >= 60:
print("C")
elif marks >= 90:
print("A") # never reached
An if inside another if. The inner one is only reached when the outer one passed.
dept, salary = "Tech", 62990
if dept == "Tech":
if salary > 50000:
print("senior tech")
else:
print("junior tech")
else:
print("not tech")
marks = 61
if marks >= 90:
print("A")
elif marks >= 75:
print("B")
elif marks >= 60:
print("C")
elif marks >= 40:
print("D")
else:
print("Fail")
y = int(input("year: "))
if y % 400 == 0:
print(y, "is a leap year")
elif y % 100 == 0:
print(y, "is not a leap year")
elif y % 4 == 0:
print(y, "is a leap year")
else:
print(y, "is not a leap year")
Walks through a collection one item at a time. The variable after for is a name you choose.
depts = ["HR", "Tech", "Sales", "Marketing"]
for d in depts:
print(d)
Produces a run of numbers. The stop value is NEVER included — range(5) gives 0 to 4.
for i in range(5):
print(i, end=" ")
print()
for i in range(1, 6):
print(i, end=" ")
print()
for i in range(0, 20, 5): # start, stop, step
print(i, end=" ")
range(len(...)) gives you the positions, which you need when you want the position as well as the value.
depts = ["HR", "Tech", "Sales"]
for i in range(len(depts)):
print(i, depts[i])
Repeats while a condition stays True. YOU have to change something inside, or it never stops.
count = 1
while count <= 5:
print(count, end=" ")
count = count + 1
Leaves the loop immediately, no matter how many items are left.
for n in [12, 7, 40, 3, 55]:
if n > 30:
print("found one over 30:", n)
break
print("checked", n)
Skips the rest of THIS turn and jumps to the next one. The loop keeps going.
for n in range(1, 11):
if n % 2 != 0:
continue # skip the odd ones
print(n, end=" ")
A loop inside a loop. The inner one runs completely for every single turn of the outer one.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end="\t")
print()
for i in range(1, 11):
print("7 x", i, "=", 7 * i)
total = 0
for n in range(1, 101):
total = total + n
print(total)
for n in range(1, 21):
if n % 3 == 0:
continue
print(n, end=" ")
n = 10
while n >= 1:
print(n, end=" ")
n = n - 1
print("Go")
Ordered, changeable, and allows duplicates. Counting starts at 0; -1 is the last one.
marks = [45, 72, 88, 61, 95]
print(marks)
print(marks[0])
print(marks[-1])
print(len(marks))
Take a range of items. The stop is not included, so [1:4] gives positions 1, 2 and 3.
marks = [45, 72, 88, 61, 95]
print(marks[1:4])
print(marks[:3])
print(marks[2:])
print(marks[-2:])
print(marks[::2])
print(marks[::-1]) # reversed
Unlike a string, a list can be edited in place.
marks = [45, 72, 88]
marks[0] = 50
print(marks)
append adds one to the end, insert puts one at a position, extend adds a whole list.
m = [45, 72]
m.append(88)
print(m)
m.insert(1, 60)
print(m)
m.extend([91, 33])
print(m)
remove deletes by VALUE, pop deletes by POSITION and hands it back, clear empties the list.
m = [45, 72, 88, 61]
m.remove(72)
print(m)
taken = m.pop(0)
print("popped", taken, "->", m)
print(m.pop()) # no number = the last one
sort changes the list itself. sorted() leaves it alone and hands back a new one.
m = [45, 72, 88, 61, 72]
m.sort()
print(m)
m.sort(reverse=True)
print(m)
print("how many 72s:", m.count(72))
print("where is 88:", m.index(88))
Totals and extremes.
marks = [45, 72, 88, 61, 95]
print("total ", sum(marks))
print("highest", max(marks))
print("lowest ", min(marks))
print("average", sum(marks) / len(marks))
m = [45, 72, 88, 61, 95]
print("highest", max(m))
print("lowest ", min(m))
print("average", sum(m) / len(m))
m = [45, 72, 88, 61, 95]
avg = sum(m) / len(m)
print("average is", avg)
for x in m:
if x > avg:
print(x, "is above")
m = [45, 72, 88, 61]
out = []
for i in range(len(m) - 1, -1, -1):
out.append(m[i])
print(out)
Round brackets instead of square. Everything about reading it is the same; writing is forbidden.
point = (10, 20, 30)
print(point)
print(point[0])
print(point[1:])
print(len(point))
A tuple does not support item assignment.
point = (10, 20, 30)
point[0] = 99
When the values must not be edited by accident — fixed settings, coordinates, a database row.
WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(len(WEEKDAYS), "working days")
print("Wed" in WEEKDAYS)
print(WEEKDAYS.count("Mon"), WEEKDAYS.index("Thu"))
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(len(days))
print("Sun" in days)
Curly brackets. No duplicates, and NO ORDER — so you cannot ask for set[0], and printing one gives the items in whatever order Python feels like. Wrap it in sorted() when you need a fixed order.
depts = {"HR", "Tech", "HR", "Sales", "Tech"}
print(len(depts)) # the 2 repeats are gone
print(sorted(depts)) # sorted, so it looks the same every run
print("HR" in depts)
Wrapping a list in set() gives its distinct values.
entries = ["HR", "Tech", "HR", "Sales", "Tech", "HR"]
print(sorted(set(entries)))
print("distinct departments:", len(set(entries)))
remove complains if the item is not there. discard does not.
s = {"HR", "Tech"}
s.add("Sales")
print(s == {"HR", "Tech", "Sales"})
s.discard("Finance") # not there, no error
s.remove("HR")
print(sorted(s))
The school set theory, as code. Useful for comparing two groups of anything.
a = {"Rahul", "Priya", "Amit"}
b = {"Priya", "Amit", "Kavya"}
print(sorted(a | b)) # in either
print(sorted(a & b)) # in both
print(sorted(a - b)) # only in a
e = ["HR", "Tech", "HR", "Sales", "Tech", "HR"]
d = set(e)
print(sorted(d))
print(len(d), "distinct")
a = {"Rahul", "Priya", "Amit"}
b = {"Priya", "Amit", "Kavya"}
print("both:", sorted(a & b))
print("only a:", sorted(a - b))
Instead of a position you use a name. That name is the key, and it has to be unique.
emp = {"name": "Rahul", "dept": "HR", "salary": 47764}
print(emp)
print(emp["name"])
print(len(emp))
Square brackets raise an error if the key is missing. get() hands back None, or whatever you choose.
emp = {"name": "Rahul", "dept": "HR"}
print(emp.get("dept"))
print(emp.get("city")) # None, not an error
print(emp.get("city", "not recorded"))
Assign to a key that exists and it updates. Assign to a new one and it is added.
emp = {"name": "Rahul", "dept": "HR"}
emp["salary"] = 47764 # new
emp["dept"] = "Tech" # changed
print(emp)
del emp["dept"]
print(emp)
items() is used when both the key and the value are needed.
emp = {"name": "Rahul", "dept": "HR", "salary": 47764}
print(list(emp.keys()))
print(list(emp.values()))
for k, v in emp.items():
print(k, "->", v)
A dictionary of counts, built in one pass over the data.
depts = ["HR", "Tech", "HR", "Sales", "Tech", "HR"]
counts = {}
for d in depts:
counts[d] = counts.get(d, 0) + 1
print(counts)
emp = {"name": "Priya", "dept": "Tech", "salary": 62990}
for k, v in emp.items():
print(k, "->", v)
word = "statistics"
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
A block of code with a name, written once and used as many times as you like. Note the colon and the indent.
def greet():
print("Welcome to Data Analytics")
greet()
greet()
The name in the brackets is a parameter. The value you send is the argument.
def greet(name):
print("Welcome,", name)
greet("Rahul")
greet("Priya")
Hands a value BACK so it can be stored or used. A function with no return hands back None.
def add(a, b):
return a + b
total = add(10, 20)
print(total)
print(add(5, 6) * 2)
print shows something; return gives it back to the code.
def shows(a, b):
print(a + b)
def gives(a, b):
return a + b
x = shows(2, 3)
y = gives(2, 3)
print("x is", x) # None - nothing came back
print("y is", y)
Separate them with commas and they come back as a tuple, which you can unpack straight away.
def stats(nums):
return min(nums), max(nums), sum(nums) / len(nums)
lo, hi, avg = stats([45, 72, 88, 61])
print(lo, hi, avg)
def average(marks):
return sum(marks) / len(marks)
print(average([45, 72, 88, 61]))
def is_even(n):
return n % 2 == 0
for n in range(1, 7):
print(n, is_even(n))
def hike(salary, pct=10):
return salary + salary * pct / 100
print(hike(47764))
print(hike(47764, 20))
Matched by ORDER. Swap them round and you quietly get the wrong answer, with no error.
def detail(name, dept):
print(name, "works in", dept)
detail("Rahul", "HR")
detail("HR", "Rahul") # no error - just wrong
Matched by NAME, so the order stops mattering.
def detail(name, dept):
print(name, "works in", dept)
detail(name="Rahul", dept="HR")
detail(dept="HR", name="Rahul")
Give a parameter a value in the def line and it becomes optional.
def detail(name, dept="Not assigned"):
print(name, "-", dept)
detail("Rahul", "HR")
detail("Priya") # dept falls back
One star collects any number of positional arguments into a tuple.
def total(*nums):
print(nums, type(nums))
return sum(nums)
print(total(10, 20))
print(total(10, 20, 30, 40))
Two stars collect any number of named arguments into a dictionary.
def record(**info):
for k, v in info.items():
print(k, "->", v)
record(name="Rahul", dept="HR", salary=47764)
Positional first, then default, then *args, then **kwargs. Putting a default before a plain one is an error.
def show(a, b=2, *args, **kwargs):
print("a", a, "| b", b, "| args", args, "| kwargs", kwargs)
show(1)
show(1, 9)
show(1, 9, 100, 200, city="Chennai")
def report(name, *marks):
print(name, "scored", sum(marks), "across", len(marks), "subjects")
report("Rahul", 45, 72, 88)
report("Priya", 91, 68)
def profile(**d):
for k, v in d.items():
print(k, ":", v)
profile(name="Amit", city="Pune", exp=4)
A function with no name, written on one line. Useful for a short, single-use function.
double = lambda x: x * 2
print(double(21))
add = lambda a, b: a + b
print(add(10, 20))
Applies a function to EVERY item and gives back the same number of items.
marks = [45, 72, 88]
out = map(lambda x: x + 5, marks)
print(list(out))
print(list(map(str, marks))) # any function works
Keeps only the items where the function says True. You get FEWER items back.
marks = [45, 72, 88, 61, 33]
passed = filter(lambda x: x >= 60, marks)
print(list(passed))
print(list(filter(lambda x: x % 2 == 0, marks)))
Boils a whole list down to ONE value, two at a time. It has to be imported first.
from functools import reduce
marks = [45, 72, 88]
print(reduce(lambda a, b: a + b, marks))
print(reduce(lambda a, b: a if a > b else b, marks))
map keeps the count, filter reduces the count, reduce collapses it to one.
from functools import reduce
m = [45, 72, 88, 61]
print("map ", list(map(lambda x: x * 2, m)), " same count")
print("filter", list(filter(lambda x: x > 60, m)), " fewer")
print("reduce", reduce(lambda a, b: a + b, m), " one")
marks = [45, 72, 88, 61]
print(list(map(lambda x: x + 5, marks)))
sal = [47764, 62990, 51200, 38000]
print(list(filter(lambda x: x > 50000, sal)))
from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))
Every recursion needs a base case — the condition that stops it. Without one it never ends.
def countdown(n):
if n == 0: # base case
print("Go")
return
print(n, end=" ")
countdown(n - 1) # calls itself
countdown(5)
5! is 5 x 4 x 3 x 2 x 1, and each step is the same problem one size smaller.
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(5))
print(fact(7))
Each number is the sum of the two before it. Two base cases this time.
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(10):
print(fib(i), end=" ")
Python raises RecursionError rather than running forever.
import sys
sys.setrecursionlimit(100)
def forever(n):
return forever(n - 1) # nothing stops it
forever(5)
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(10))
def rev(s):
if len(s) == 0:
return ""
return s[-1] + rev(s[:-1])
print(rev("analytics"))
A for loop and an append, written on one line. Read it as: what I want, then where it comes from.
# the long way
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)
# the same thing
squares = [n * n for n in range(1, 6)]
print(squares)
Put the if at the END and it filters — only the items that pass get built.
marks = [45, 72, 88, 61, 33]
print([m for m in marks if m >= 60])
print([m * 2 for m in marks if m % 2 == 0])
When you want a value for EVERY item, the if-else goes at the FRONT.
marks = [45, 72, 88, 61]
print(["pass" if m >= 60 else "fail" for m in marks])
Anything you can loop over, you can comprehend over.
print([c.upper() for c in "python"])
print([x for x in "statistics" if x in "aeiou"])
print([[i * j for j in range(1, 4)] for i in range(1, 4)])
Same idea with curly brackets and a key : value pair.
depts = ["HR", "Tech", "Sales"]
print({d: len(d) for d in depts})
print({n: n * n for n in range(1, 6)})
print([n * n for n in range(1, 21) if n % 2 == 0])
d = ["HR", "Tech", "Sales"]
print([x.upper() for x in d])
m = [45, 72, 88, 61, 33]
print(["pass" if x >= 60 else "fail" for x in m])
A string is a sequence of characters. Counting starts at 0, and -1 is the last one.
name = "Analytics"
print(name[0])
print(name[4])
print(name[-1])
print(len(name))
Take a piece. The stop is NOT included, so [0:4] gives characters 0, 1, 2 and 3.
name = "Analytics"
print(name[0:4])
print(name[:4])
print(name[4:])
print(name[-3:])
How big a jump to take. A negative step walks backwards, which is how you reverse a string.
name = "Analytics"
print(name[::2])
print(name[1::2])
print(name[::-1]) # reversed
Unlike a list, you cannot assign to one character. Build a new string instead.
name = "Analytics"
name[0] = "X"
+ joins two strings, * repeats one. Both make a NEW string.
a, b = "Data", "Analytics"
print(a + " " + b)
print("-" * 20)
print(a * 3)
Checks whether one string appears inside another. Hands back True or False.
s = "Data Analytics"
print("Data" in s)
print("Python" in s)
print("data" in s) # case matters
s = "Data Analytics"
print(s[::-1])
print(s[-5:])
for w in ["madam", "python"]:
print(w, w == w[::-1])
s = "data analytics"
n = 0
for ch in s:
if ch in "aeiou":
n = n + 1
print(n)
None of these change the original string; each returns a new one.
s = "data analytics"
print(s.upper())
print(s.title())
print(s.capitalize())
print("HELLO".lower())
print(s) # untouched
Takes whitespace off both ends.
s = " Rahul Sharma "
print("[" + s + "]")
print("[" + s.strip() + "]")
print("[" + s.lstrip() + "]")
print("[" + s.rstrip() + "]")
Swaps every occurrence of one piece of text for another.
s = "Data Analytics"
print(s.replace("Data", "Business"))
print("a-b-c".replace("-", " "))
print(s.replace("a", "*"))
split cuts a string into a list; join glues a list back into a string. Opposites.
s = "HR,Tech,Sales"
parts = s.split(",")
print(parts)
print(" | ".join(parts))
print("Rahul Kumar Sharma".split()) # no argument = split on spaces
find gives the POSITION of the first match, or -1 if it is not there. count gives how many.
s = "statistics"
print(s.find("t"))
print(s.find("z")) # -1, not an error
print(s.count("t"))
print(s.count("s"))
Checks the beginning or the end. Commonly used for filenames and codes.
f = "employees.csv"
print(f.endswith(".csv"))
print(f.startswith("emp"))
print("EMP1001".startswith("EMP"))
Each one asks a yes/no question about what the string contains.
print("12345".isdigit())
print("Rahul".isalpha())
print("Rahul123".isalnum())
print(" ".isspace())
print("HELLO".isupper())
raw = " rahul SHARMA "
print("[" + raw.strip().title() + "]")
s = "HR,Tech,Sales,Marketing"
parts = s.split(",")
print(parts)
print(" | ".join(parts))
w = "statistics"
c = {}
for ch in w:
c[ch] = c.get(ch, 0) + 1
print(c)
print("most common:", max(c, key=c.get))
An f before the quote allows an expression inside curly brackets.
name, dept, salary = "Rahul", "HR", 47764
print(f"{name} works in {dept} and earns {salary}")
print(f"next year: {salary * 1.1}")
:.2f sets the number of decimal places.
salary = 47764
hiked = salary * 1.1
print(f"raw {hiked}")
print(f"rounded {hiked:.2f}")
print(f"no dp {hiked:.0f}")
A number after <, > or ^ sets the field width.
rows = [("HR", 45), ("Marketing", 42), ("Tech", 49)]
for d, n in rows:
print(f"{d:<12}{n:>5}")
The curly brackets are filled in order.
print("{} works in {}".format("Rahul", "HR"))
print("{1} then {0}".format("second", "first"))
print("{:.2f}".format(3.14159))
rows = [("HR", 45), ("Marketing", 42), ("Tech", 49)]
for d, n in rows:
print(f"{d:<12}{n:>4}")
s = 47764
print(f"new salary: {s * 1.12:.2f}")
A character that stands for a class of characters rather than itself.
print(r"\d any digit 0-9")
print(r"\w any letter, digit or underscore")
print(r"\s any space, tab or newline")
print(r". any character at all")
print(r"^ start of the string")
print(r"$ end of the string")
print(r"+ one or more")
print(r"* zero or more")
print(r"? zero or one")
print(r"{n} exactly n of them")
Returns every match as a list.
import re
s = "Rahul 1001, Priya 1002, Amit 1003"
print(re.findall(r"\d+", s))
print(re.findall(r"[A-Z][a-z]+", s))
Finds the FIRST match anywhere and hands back a match object, or None.
import re
s = "Employee ID is EMP1001"
m = re.search(r"EMP\d+", s)
print(m)
print(m.group())
print(re.search(r"XYZ", s)) # None
Same as search, but it only looks at the beginning of the string.
import re
print(re.match(r"EMP", "EMP1001"))
print(re.match(r"1001", "EMP1001")) # None - not at the start
Replaces every match with something else. A find-and-replace that understands patterns.
import re
s = "Call 9876543210 or 9123456789"
print(re.sub(r"\d", "X", s))
print(re.sub(r"\d{10}", "[hidden]", s))
Splits on a pattern rather than on one fixed character.
import re
print(re.split(r"[,;]", "HR,Tech;Sales,Marketing"))
print(re.split(r"\s+", "too many spaces"))
^ and $ anchor the pattern so the whole string must match.
import re
pattern = r"^[\w.]+@[\w]+\.[a-z]{2,}$"
for e in ["rahul@tap.com", "priya.s@tap.co.in", "not-an-email", "a@b"]:
print(e.ljust(20), bool(re.match(pattern, e)))
import re
print(re.findall(r"\d+", "Order 12 shipped on 2026-10-30 for 450 rupees"))
import re
s = "Call 9876543210 or 9123456789 today"
print(re.sub(r"\d{10}", "[hidden]", s))
import re
for x in ["EMP1001", "EMP10", "emp1001", "EMP12345"]:
print(x.ljust(10), bool(re.match(r"^EMP\d{4}$", x)))
"w" writes and WIPES whatever was there. "a" adds to the end. "r" reads. Choose carefully.
f = open("notes.txt", "w")
f.write("first line\n")
f.write("second line\n")
f.close()
f = open("notes.txt", "r")
print(f.read())
f.close()
Opening in w mode empties the file before you write a single thing.
open("data.txt", "w").write("original content\n")
open("data.txt", "w").write("new content\n") # the original is GONE
print(open("data.txt").read())
Append mode keeps what is already there and writes underneath it.
open("log.txt", "w").write("line 1\n")
open("log.txt", "a").write("line 2\n")
open("log.txt", "a").write("line 3\n")
print(open("log.txt").read())
read gives one big string, readline gives one line, readlines gives a list of lines.
open("f.txt", "w").write("alpha\nbeta\ngamma\n")
f = open("f.txt")
print(repr(f.readline()))
f.close()
f = open("f.txt")
print(f.readlines())
f.close()
The normal way to read a file line by line. strip() takes the newline off each one.
open("f.txt", "w").write("HR\nTech\nSales\n")
f = open("f.txt")
for line in f:
print("[" + line.strip() + "]")
f.close()
The file is closed automatically, even if the code inside fails.
with open("f.txt", "w") as f:
f.write("written safely\n")
with open("f.txt") as f:
print(f.read().strip())
print("file closed?", f.closed)
with open("d.txt", "w") as f:
for d in ["HR", "Tech", "Sales"]:
f.write(d + "\n")
with open("d.txt") as f:
for line in f:
print("[" + line.strip() + "]")
open("d.txt", "w").write("HR\nTech\n")
with open("d.txt", "a") as f:
f.write("Sales\n")
f.write("Marketing\n")
print(len(open("d.txt").readlines()), "lines")
open("n.txt", "w").write("10\n20\n30\n")
total = 0
with open("n.txt") as f:
for line in f:
total = total + int(line.strip())
print(total)
An uncaught error stops the program; nothing after it runs.
nums = ["10", "20", "abc", "30"]
for n in nums:
print(int(n)) # stops dead on "abc"
Try the risky line. If it fails, run the except block instead of stopping.
nums = ["10", "20", "abc", "30"]
for n in nums:
try:
print(int(n))
except:
print(n, "is not a number - skipped")
Naming the error avoids hiding problems you did not expect.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "cannot divide by zero"
print(divide(10, 2))
print(divide(10, 0))
Different problems, different handling. Python runs the first one that matches.
for value, divisor in [("10", 2), ("abc", 2), ("10", 0)]:
try:
print(int(value) / divisor)
except ValueError:
print("not a number:", value)
except ZeroDivisionError:
print("divisor was zero")
else runs only when nothing failed. finally runs either way — it is where you clean up.
def read(n):
try:
v = int(n)
except ValueError:
print("bad input")
else:
print("worked:", v)
finally:
print("-- done --")
read("25")
read("xyz")
The exception name identifies what went wrong.
tests = [lambda: int("abc"),
lambda: 10 / 0,
lambda: [1, 2, 3][9],
lambda: {"a": 1}["b"],
lambda: "5" + 5]
for t in tests:
try:
t()
except Exception as e:
print(type(e).__name__, "-", e)
for entry in ["25", "hello"]:
try:
print("doubled:", int(entry) * 2)
except ValueError:
print(entry, "is not a number")
def safe(a, b):
try:
return int(a) / int(b)
except ZeroDivisionError:
return "cannot divide by zero"
except ValueError:
return "give me numbers"
print(safe(10, 2))
print(safe(10, 0))
print(safe("x", 2))
try:
with open("missing.txt") as f:
print(f.read())
except FileNotFoundError:
print("that file is not here")
A class is a blueprint; an object is one instance built from it.
class Employee:
pass
e1 = Employee()
e2 = Employee()
print(type(e1))
print(e1 is e2) # two different objects
__init__ runs when an object is created. self refers to that object.
class Employee:
def __init__(self, name, dept, salary):
self.name = name
self.dept = dept
self.salary = salary
e = Employee("Rahul", "HR", 47764)
print(e.name, e.dept, e.salary)
A function defined inside a class. It takes self as its first parameter.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def hike(self, pct):
self.salary = self.salary + self.salary * pct / 100
return self.salary
def show(self):
print(self.name, "earns", self.salary)
e = Employee("Rahul", 47764)
e.show()
e.hike(10)
e.show()
Two objects created from the same class do not share their data.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
a = Employee("Rahul", 47764)
b = Employee("Priya", 62990)
a.salary = 50000
print(a.name, a.salary)
print(b.name, b.salary) # untouched
Objects in a list can be looped over like any other data.
class Employee:
def __init__(self, name, dept, salary):
self.name, self.dept, self.salary = name, dept, salary
staff = [Employee("Rahul", "HR", 47764),
Employee("Priya", "Tech", 62990),
Employee("Amit", "Sales", 51200)]
for e in staff:
print(e.name.ljust(8), e.dept.ljust(7), e.salary)
total = sum(e.salary for e in staff)
print("total payroll:", total)
print("average :", total / len(staff))
List operations apply the same way when the items are objects.
class Employee:
def __init__(self, name, dept, salary):
self.name, self.dept, self.salary = name, dept, salary
staff = [Employee("Rahul", "HR", 47764),
Employee("Priya", "Tech", 62990),
Employee("Amit", "Tech", 51200)]
tech = [e for e in staff if e.dept == "Tech"]
for e in tech:
print(e.name)
print("highest paid:", max(staff, key=lambda e: e.salary).name)
class Student:
def __init__(self, name, m1, m2, m3):
self.name = name
self.marks = [m1, m2, m3]
def average(self):
return sum(self.marks) / len(self.marks)
s = Student("Rahul", 45, 72, 88)
print(s.name, "->", s.average())
class Employee:
def __init__(self, name, salary):
self.name, self.salary = name, salary
staff = [Employee("Rahul", 47764), Employee("Priya", 62990),
Employee("Amit", 51200), Employee("Kavya", 58300)]
top = max(staff, key=lambda e: e.salary)
print(top.name, top.salary)
class Employee:
def __init__(self, name, dept, salary):
self.name, self.dept, self.salary = name, dept, salary
staff = [Employee("Rahul", "HR", 47764), Employee("Priya", "Tech", 62990),
Employee("Amit", "Tech", 51200)]
tech = [e.salary for e in staff if e.dept == "Tech"]
print(sum(tech) / len(tech))
The data and the methods that use it live in the same class. Two leading underscores mark an attribute as internal.
class Account:
def __init__(self, holder, balance):
self.holder = holder
self.__balance = balance # internal
def deposit(self, amount):
self.__balance = self.__balance + amount
def show(self):
print(self.holder, "balance:", self.__balance)
a = Account("Rahul", 1000)
a.deposit(500)
a.show()
print(hasattr(a, "__balance")) # not reachable from outside
Naming a parent class in the brackets gives the child all of its attributes and methods.
class Employee:
def __init__(self, name):
self.name = name
def show(self):
print("Employee:", self.name)
class Manager(Employee): # inherits
pass
m = Manager("Priya")
m.show() # a method it never defined
print(isinstance(m, Employee))
Calls the parent's version, so it does not have to be rewritten.
class Employee:
def __init__(self, name):
self.name = name
class Manager(Employee):
def __init__(self, name, team):
super().__init__(name) # reuse the parent
self.team = team
m = Manager("Priya", 6)
print(m.name, "manages", m.team, "people")
The child defines a method the parent already has. Same name, different behaviour.
class Employee:
def role(self):
print("does the work")
class Manager(Employee):
def role(self): # overrides
print("assigns the work")
class Intern(Employee):
pass # keeps the parent version
for p in [Employee(), Manager(), Intern()]:
p.role()
A base class names a method and leaves the detail to each child class.
class Payroll:
def calculate(self):
pass # the parent only NAMES it
class Monthly(Payroll):
def calculate(self):
return 50000
class Hourly(Payroll):
def calculate(self):
return 250 * 160
for p in [Monthly(), Hourly()]:
print(type(p).__name__, "->", p.calculate())
class Vehicle:
def describe(self):
print("a vehicle that moves")
class Car(Vehicle):
def describe(self):
print("a car with four wheels")
for v in [Vehicle(), Car()]:
v.describe()
class Employee:
def __init__(self, name, salary):
self.name, self.salary = name, salary
def show(self):
print(self.name, self.salary)
class Manager(Employee):
def __init__(self, name, salary, team):
super().__init__(name, salary)
self.team = team
def show(self):
super().show()
print(" manages", self.team, "people")
Manager("Priya", 90000, 6).show()
Builds an array from a list. An array holds one type of value and prints without commas.
import numpy as np
a = np.array([10, 20, 30, 40])
print(a)
print(type(a))
A list of lists becomes a table: rows inside, columns across.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m)
A sequence of numbers. Takes start, stop and step; the stop value is not included.
import numpy as np
print(np.arange(5))
print(np.arange(1, 11))
print(np.arange(0, 21, 5))
Arrays filled with 0 or 1. Both produce floats unless a type is given.
import numpy as np
print(np.zeros(5))
print(np.ones(4))
print(np.zeros((2, 3)))
An array of any size filled with a value of your choice.
import numpy as np
print(np.full(5, 7))
print(np.full((2, 3), -1))
Evenly spaced values between two points. The third number is how many you want, not the step.
import numpy as np
print(np.linspace(0, 10, 5))
print(np.linspace(0, 1, 3))
Random values. rand gives decimals between 0 and 1; randint gives whole numbers in a range.
import numpy as np
np.random.seed(1) # fixes the result so it can be checked
print(np.random.rand(3))
print(np.random.randint(1, 100, 5))
import numpy as np
print(np.arange(0, 21, 2))
print(np.ones((3, 3)))
How many dimensions, the rows and columns, and the total number of values. No brackets.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.ndim)
print(m.shape)
print(m.size)
The single type every value in the array shares.
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1.5, 2.5]).dtype)
print(np.array(["a", "b"]).dtype)
Converts the array to another type. Converting a float to an int removes the decimal part.
import numpy as np
a = np.array([1.7, 2.3, 3.9])
print(a.astype(int))
print(np.array([1, 2, 3]).astype(float))
import numpy as np
a = np.zeros((3, 4))
print(a.ndim, a.shape, a.size, a.dtype)
Position 0 is the first value. Negative positions count back from the end.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0])
print(a[3])
print(a[-1])
a[start:stop] returns a range of values. The stop position is not included.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[1:4])
print(a[:3])
print(a[2:])
print(a[-2:])
A third number sets the jump. A negative step reverses the array.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[::2])
print(a[1::2])
print(a[::-1])
Give the row first, then the column. A colon on its own means every row or every column.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(m[0])
print(m[1, 2])
print(m[:, 0])
print(m[0:2, 0:2])
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[:3])
print(a[-2:])
print(a[::-1])
import numpy as np
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(m[:, 1])
print(m[0:2, 0:2])
An operator applies to every element at once. No loop is needed.
import numpy as np
a = np.array([10, 20, 30, 40])
print(a + 5)
print(a - 5)
print(a * 2)
print(a / 10)
These operations return a new array. The original is unchanged until you assign the result.
import numpy as np
a = np.array([10, 20, 30])
a + 5
print(a)
a = a + 5
print(a)
Operators work position by position when the arrays are the same size.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(a + b)
print(a * b)
Maths functions take the array as an argument. The second number of round is the decimal places.
import numpy as np
a = np.array([9, 16, 25, 36])
print(np.sqrt(a))
print(np.round(a / 3))
print(np.round(a / 3, 2))
import numpy as np
s = np.array([45000, 52000, 61000])
print(s * 1.10)
Reduce a whole array to a single value.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(a.sum())
print(a.mean())
print(a.min())
print(a.max())
The middle value. It is a NumPy function, not a method on the array.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(np.median(a))
Standard deviation measures spread. Variance is the square of it.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(round(a.std(), 2))
print(round(a.var(), 2))
The position of the smallest or largest value, not the value itself.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(a.min(), a.argmin())
print(a.max(), a.argmax())
A running total. The final value equals the sum of the whole array.
import numpy as np
a = np.array([10, 20, 30, 40])
print(a.cumsum())
print(a.sum())
On a table, axis=0 works down the columns and axis=1 works across the rows.
import numpy as np
m = np.array([[10, 20, 30],
[40, 50, 60]])
print(m.sum())
print(m.sum(axis=0))
print(m.sum(axis=1))
print(m.mean(axis=1))
import numpy as np
a = np.array([23, 45, 12, 67, 34, 89])
print(a.sum(), round(a.mean(), 2))
print(a.max(), a.argmax())
import numpy as np
m = np.array([[10,20,30],[40,50,60]])
print(m.sum(axis=0))
print(m.mean(axis=1))
One number is applied to every element of the array.
import numpy as np
m = np.array([[10, 20, 30],
[40, 50, 60]])
print(m + 100)
A one-row array is reused for every row of the table when the widths match.
import numpy as np
m = np.array([[10, 20, 30],
[40, 50, 60]])
r = np.array([1, 2, 3])
print(m + r)
The sizes must match or be 1. If they do not, NumPy stops and names both shapes.
import numpy as np
m = np.array([[10, 20, 30],
[40, 50, 60]])
print(m + np.array([1, 2]))
import numpy as np
m = np.array([[10,20,30],[40,50,60],[70,80,90]])
print(m + np.array([1, 2, 3]))
Comparing an array to a value tests every element and returns an array of booleans.
import numpy as np
a = np.array([5, 12, 18, 7, 25])
print(a > 10)
Putting the condition inside the brackets returns only the values where it was True.
import numpy as np
a = np.array([5, 12, 18, 7, 25])
print(a[a > 10])
print(a[a % 2 == 0])
True counts as 1, so summing the condition counts how many values matched.
import numpy as np
a = np.array([5, 12, 18, 7, 25])
print((a > 10).sum())
Use & for and, | for or. Each condition needs its own brackets.
import numpy as np
a = np.array([5, 12, 18, 7, 25])
print(a[(a > 10) & (a < 20)])
print(a[(a < 8) | (a > 20)])
Takes a condition, a value for True and a value for False. The array keeps its length.
import numpy as np
a = np.array([5, 12, 18, 7, 25])
print(np.where(a > 10, "high", "low"))
print(np.where(a > 10, a, 0))
import numpy as np
a = np.array([12, 45, 7, 88, 23, 56])
print(a[a > 20])
print((a > 20).sum())
import numpy as np
a = np.array([12, 45, 7, 88])
print(np.where(a >= 40, "pass", "fail"))
Returns the values in order, smallest first. The original array is unchanged.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(np.sort(a))
print(a)
Returns the positions that would put the array in order.
import numpy as np
a = np.array([15, 8, 42, 4, 23])
print(np.argsort(a))
print(a[np.argsort(a)])
The distinct values, in order, with repeats removed.
import numpy as np
a = np.array([3, 1, 2, 3, 1, 1, 4])
print(np.unique(a))
import numpy as np
a = np.array([5, 2, 9, 1, 7])
print(np.sort(a))
print(np.argsort(a))
Rearranges the same values into different rows and columns. Rows x columns must equal size.
import numpy as np
a = np.arange(1, 7)
print(a.reshape(2, 3))
print(a.reshape(3, 2))
If the new shape needs a different number of values, NumPy refuses.
import numpy as np
a = np.arange(1, 7)
print(a.reshape(4, 2))
Turns a table back into a single row. It returns a copy, so the original is unchanged.
import numpy as np
m = np.arange(1, 7).reshape(2, 3)
print(m.flatten())
print(m)
import numpy as np
a = np.arange(1, 13)
m = a.reshape(3, 4)
print(m)
print(m.flatten())
A single column of values. Pandas adds a numbered index on the left.
import pandas as pd
s = pd.Series([10, 20, 30])
print(s)
The index can be any set of labels instead of 0, 1, 2.
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"])
print(s)
print(s["b"])
A table. Built from a dictionary, each key becomes a column name.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya"],
"dept": ["HR", "Tech"]
})
print(df)
Loads a comma-separated file into a DataFrame.
import pandas as pd
open("staff.csv", "w").write("name,dept\nRahul,HR\nPriya,Tech\n")
df = pd.read_csv("staff.csv")
print(df)
import pandas as pd
df = pd.DataFrame({
"name": ["Anita", "Rohit", "Meena"],
"city": ["Chennai", "Pune", "Delhi"],
"mark": [72, 85, 64]
})
print(df)
The first or last rows. The default is five; pass a number for more or fewer.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.head(3))
print()
print(df.tail(2))
The number of rows and columns, the column names, and the type held in each.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.shape)
print(list(df.columns))
print(df.dtypes)
Column names, their types and how many non-empty values each one holds.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
df.info()
Count, mean, standard deviation, minimum, quartiles and maximum for the numeric columns.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.describe())
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.shape)
print(list(df.columns))
print(df.describe())
Square brackets with the column name return that column as a Series.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["name"])
Two or more column names must be passed as a list, so there are two sets of brackets.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[["name", "salary"]])
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[["name", "dept"]])
Selects rows by their index label.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.loc[0])
print()
print(df.loc[0:2])
Selects rows by their position. Unlike loc, the stop position is not included.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.iloc[0:2])
print()
print(df.iloc[-1])
Give the rows first, then the columns.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.loc[0:2, ["name", "salary"]])
print()
print(df.iloc[0:2, 0:2])
Reads one value, given the row label and the column name.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.at[0, "name"])
print(df.at[3, "salary"])
The same as at, but both the row and the column are given as numbers.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.iat[0, 0])
print(df.iat[3, 2])
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.iloc[0:2])
print(df.at[2, "salary"])
Comparing a column to a value returns True or False for every row.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["salary"] > 50000)
Putting the condition inside the brackets keeps only the rows where it was True.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[df["salary"] > 50000])
Use & for and, | for or. Each condition must be inside its own brackets.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[(df["dept"] == "Tech") & (df["salary"] > 55000)])
print()
print(df[(df["dept"] == "HR") | (df["exp"] > 5)])
The word and expects one True or False, not a whole column of them.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[(df["dept"] == "Tech") and (df["salary"] > 55000)])
A condition can be summed, because True counts as 1.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print((df["salary"] > 50000).sum())
print(len(df[df["salary"] > 50000]))
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[df["salary"] > 50000])
print((df["salary"] > 50000).sum())
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df[(df["dept"] == "Tech") & (df["exp"] > 5)])
Orders the rows by a column. Smallest first unless told otherwise.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.sort_values("salary"))
Reverses the order, largest first.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.sort_values("salary", ascending=False))
Pass a list. The second column breaks ties in the first.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.sort_values(["dept", "salary"]))
Sorting returns a new table. Assign it if the order is to be kept.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
df.sort_values("salary")
print(df["salary"].tolist())
df = df.sort_values("salary")
print(df["salary"].tolist())
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.sort_values("salary", ascending=False)["name"].head(2).tolist())
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df.sort_values(["dept", "salary"]))
How many times each value appears in a column, most frequent first.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["dept"].value_counts())
The distinct values in a column, and how many there are.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["dept"].unique())
print(df["dept"].nunique())
The same summaries as NumPy, applied to one column.
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["salary"].sum())
print(round(df["salary"].mean(), 2))
print(df["salary"].min(), df["salary"].max())
print(df["salary"].median())
import pandas as pd
df = pd.DataFrame({
"name": ["Rahul", "Priya", "Amit", "Kavya", "Arjun"],
"dept": ["HR", "Tech", "Sales", "Tech", "HR"],
"salary": [47764, 62990, 51200, 58300, 45100],
"exp": [4, 7, 3, 6, 2]
})
print(df["dept"].value_counts())
print(round(df["salary"].mean(), 2))