1/66
Looks like no tags are added yet.
what does bool(90) return?
true, any number but zero returns true
what does bool(0) return?
false, zero returns false
what does bool("LiterallyAnyString") return?
true, any string returns true
what does bool("") return?
false, empty strings return false
ListName[-1] returns what value in a list
the last value
how to string concatenate the 2 string variables string1 and string2, with an underscore in between?
string1 + "_" + string2
what do .upper(), .lower(), .title(), and .capitalize() do?
converts string characters to all uppercase, all lowercase, first letter of all words to uppercase & rest to lowercase, and first letter of first words to uppercase & rest to lowercase.
.split() does what
turns a string into a list with all words separated into individual list strings
status = ["A", "B"]. What does status[50 > 49] evaluate to?
B, because 50>49 is true, and true has index 1, false has index 0.
what data type does the input() function always return as?
string
to make an input() function save as float, what do you have to do?
int(input())
what letter do you put before a format string, and what braces do you use around int/floats?
"f" and curly braces, e.g: print(f"Sensor Temperature: {sensor_temp} [deg C]")
inside a f-string, what do you put directly after your int/float name to round to 3 decimal places?
:.3f
what does random.uniform(), random.randrange(), random.choice(), random.choices(), random.sample(), and random.shuffle() do?
random float from specified range of ints or floats, random int with a step random.randrange(start, stop, step), returns 1 random letter from a string, value from a list, or int/float from a range, returns a list of k items from a sequence w/ replacement random.choices(colors, k=2), same thing as random.choices() but does it without replacement, random.shuffle() returns the list given to it shuffled.
how do you print the list of reserved python keywords, and how do you check if a keyword is reserved?
print(keyword.kwlist()), using the iskeyword("wordYouAreChecking") function
how do you print all builtins
print(dir(builtins))
what element shape on a python flowchart is used for the flowline, start and end of a program (terminal), operation or calculation (process), condition that determines path of program (decision), info entered or being displayed (input/output), and calling a function defined elsewhere (predefiend process)
arrow, slot, square, diamond, parallelogram, rectangle w/ second rectangle with longer length
what is the sentinel value
the value that will stop an indefinite while loop when entered by user, usually a value like -1 or "quit" that wont be encountered normally.
what does [ for in i range(1,6): print(i) ] print?
1 2 3 4 5
what do each of these list modifiers do to the list called m?: m.remove(x), m.pop(i), m.sort(), sorted(m), m.append(x), m.extend(t), m.copy().
removes the first occurence of x from list m, removes the value at index i from m, changes m to be sorted alphabetically or least to greatest, creates a new list sorted same way as .sort(), adds x at end of list m, add elements of list t to end of list m, copies list elements into new list ready to be modifed.
for a list m, m[i:j:k] returns what
elements from index i to j-1, with a step k
for a list m, what do these do: m[-i:], m[:-i], m[::-1]
returns the elements from the last index to the end of the list, returns the elements from the beginning of the list to the last index, returns the elements in reverse order.
can lists and 2d/multidimensional lists hold different data types? (string, int, float, bool)
yes
how do you create a numpy array? (remember to import)
import numpy as np ArrayName = np.array([1,2,3,4,5])
whats the difference between np.shape(ArrayName) and ArrayName.shape ?
none, they both return the amount of elements for each axis: e.g: a 2d array with 2 rows and 3 columns will return 2,3
for numpy, what do .size, .ndim, and .dtype return?
returns the total number of elements in the array, returns the number of dimensions, and returns the data types of the elements in the array
what do these do: np.zeros(shape), np.ones(shape), np.full(shape,value), np.arange(start,stop,step), and np.linspace(start,stop,num)
using specified shape it fills the array with zeros, ones, and specified values. np.arange creates an array with a range of values with a specified step. np.linspace does same thing but no step, instead num is the num of elements.
what does np.transpose do? and np.dot(array1, array2) do?
swap rows and colums, and find dotproduct of 2 arrays.
what does broadcasting do with 2 arrays
Can use operators (addition, subtraction etc.) to stretch the smaller array across the larger arrays
how do you use slicing to create a 2x2 matrix of the top left 2x2 of a 3x3 matrix
sub_matrix = matrix[0:2, 0:2]
where is numpy used better than pandas and vice versa?
numpy is good for fast efficient number calculations of a sinlge datatype, while pandas uses numpy and wraps it, making it user friendly, able to handle multiple different datatypes, and has built in tools for
how do you make a dictionary?
curly braces on the outside, then for each row its column name, colon, and then your data in square brackets. row ex: "Name": ["John", "Anna", "Peter", "Linda"].
how do you create a dataframe
DataFrameName = pd.DataFrame()
how do you import data from csv and excel?
df_1 = pd.read_csv("file_path.csv")
df_2 = pd.read_excel("file_path.xlsx")
how do you display the first 5 rows of a dataframe, and the first n rows?
printing df.head() and df.head(n)
how do you print dataframe columns
print(df.columns)
does df.shape() display rows or columns first?
rows first then columns, seperated by comma.
how to write to csv, and what do these do in a write to csv function:? index=, columns=, sep=, and na_rep=
df.to_csv(
"output.csv", # the name of the csv you write to (creates a new one if nothing if that name isint found at that file path)
index=False, # don't write row index in first column
columns=["A", "B"], # select specific columns
sep=",", # delimiter (default is comma)
na_rep="NA" # representation for missing values
)
do you use df.to_csv() to write to a text file?
yes but make sure the first argument in the parantheses has a file path with ".txt" at the end. same thing with excel for ".xlsx" and df.to_excel.
how do you write to a specific sheet
with pd.ExcelWriter("output.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="Sheet1", index=False)
how do you select a single column from a dataframe, how do you select multiple?
ages = df["Age"], subset = df[["Name", "Age"]]
how do you merge 2 dataframes holding dictionary objects based on the column called "ID"?
combined = pd.merge(df1, df2, on="ID"), where combined is a 2d array
how do you filter a dataframe based on age being less than 30, writing the data from the dataframe "df" to the dataframe "filtered_df"?
filtered_df = df[df["Age"]
what is the difference between = and ==?
= is used for defining variables, == is used as a comparison operator returning a true or false.
how would you sort age values in descending order in a dataframe?
sorted_df = df.sort_values(by="Age", ascending=False)
what do these do:? print(df.isnull()), print(df.isnull().sum()), df.dropna(), df["Int"].fillna(0)
displays missing values, counts missing values, drops missing values, fills missing values in column "int" with 0.
how to drop duplicate rows, rename columns, and change datatypes in dataframes?
df.drop_duplicates(), df.rename(columns={"oldName" : "newName"}), df["Pressure"] = df["Pressure"].astype(float)
What does .groupby() do for dataframes?
it groups 2 dictionaries by index number creating a 2d dataframe, can apply operations to a column aswell. e.g. df.groupby('Department')['Salary'].mean()
what does df.describe() do?
summary statistics for all the numeric columns in a dataframe
how to import matplotlib?
import matplotlib.pyplot as plt
how do you create a line plot of temp vs time in matplotlib?
plt.plot(time, temperature)
how do you create an x or y axis label, and a title for matplotlib graph that considers fontsize and padding?
plt.xlabel("XlLabel", fontsize = 14, labelpad = 10), plt.title("Title", fontsize = 14, pad = 15)
how do you increase tick label size and tighten the layout to prevent label clipping in matplotlib?
plt.tick_params(labelsize=11), clipping plt.tight_layout()
how do you convert a "Date" column in a dataframe to time, and how do you do it with a none standard format like month/day/year?
df["Date"] = pd.to_datetime(df["Date"]), df["Date"] = pd.to_datetime(df["Date"], format = %m/%d/%y)
hours = %H, minutes = %M, seconds = %S
how would you filter a dataframe by year from the "Date column" considering the fact that it used pd.to_datetime() to convert to time.
flitered_water_data = df[df["Date"].dt.year == 2025]
what do these marker codes represent in matplotlib: o, s, ^, [downarrow], D, d, +, x, *, p, h, and .?
circle, square, triangle, upsidedown triangle, diamond, thin diamond, plus, cross, star, pentagon, hexagon, and point.
how to plot using matplotlib to make a scatterplot with triangle markers of size 20?
plt.scatter(x, y, marker='^', s=20)
how to make bar chart and histogram in matplotlib
plt.bar(x,y), plt.hist(name, bins=20, edgecolor='black', color='steelblue')
how to add a legend
plt.legend(framealpha=0.9, fontsize=12, loc="upper left")
how to make second y axis
ax2 = ax1.twinx()
how to use polyfit and what does it return
np.polyfit(x,y,1) 1 is the degree, and it returns an array where the first index, 0, is the highest degree, slope for degree 1 regression.
how to import matplotlib
import matplotlib.pyplot as plt
how to make a grid in matplotlib of an alpha value of 0.3 with a dotted line
plt.grid(alpha=0.3, linestyle="--")
how to make an evenly spaced x-values for a matplotlib graph
np.linspace(x.min(), x.max(), 100)
how to use plt.plot to plot a matplotlib graph using the x list x_line, y list y_line, tomato colored line, with a label that has the y=mx+b equation and r^2 with a line width of 2.
plt.plot(x_line, y_line, color="tomato", label=f"Regression: y = {slope:.3f}x + {intercept:.3f}, r^2={r2:.3f}", linewidth=2)
how is .values used to prepare data
X = df["airspeed_kmh"].values, since .values pulls out the data from a dataframe column while ignoring the key from the dict.
what argument is used to put linear regression line above data point
zorder, zorder=2 is above zorder=1