ENGR 131 Exam 2: Python - Purdue University

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/66

encourage image

There's no tags or description

Looks like no tags are added yet.

67 Terms

1
New cards

what does bool(90) return?

true, any number but zero returns true

2
New cards

what does bool(0) return?

false, zero returns false

3
New cards

what does bool("LiterallyAnyString") return?

true, any string returns true

4
New cards

what does bool("") return?

false, empty strings return false

5
New cards

ListName[-1] returns what value in a list

the last value

6
New cards

how to string concatenate the 2 string variables string1 and string2, with an underscore in between?

string1 + "_" + string2

7
New cards

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.

8
New cards

.split() does what

turns a string into a list with all words separated into individual list strings

9
New cards

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.

10
New cards

what data type does the input() function always return as?

string

11
New cards

to make an input() function save as float, what do you have to do?

int(input())

12
New cards

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]")

13
New cards

inside a f-string, what do you put directly after your int/float name to round to 3 decimal places?

:.3f

14
New cards

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.

15
New cards

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

16
New cards

how do you print all builtins

print(dir(builtins))

17
New cards

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

18
New cards

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.

19
New cards

what does [ for in i range(1,6): print(i) ] print?

1 2 3 4 5

20
New cards

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.

21
New cards

for a list m, m[i:j:k] returns what

elements from index i to j-1, with a step k

22
New cards

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.

23
New cards

can lists and 2d/multidimensional lists hold different data types? (string, int, float, bool)

yes

24
New cards

how do you create a numpy array? (remember to import)

import numpy as np ArrayName = np.array([1,2,3,4,5])

25
New cards

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

26
New cards

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

27
New cards

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.

28
New cards

what does np.transpose do? and np.dot(array1, array2) do?

swap rows and colums, and find dotproduct of 2 arrays.

29
New cards

what does broadcasting do with 2 arrays

Can use operators (addition, subtraction etc.) to stretch the smaller array across the larger arrays

30
New cards

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]

31
New cards

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

32
New cards

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"].

33
New cards

how do you create a dataframe

DataFrameName = pd.DataFrame()

34
New cards

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")

35
New cards

how do you display the first 5 rows of a dataframe, and the first n rows?

printing df.head() and df.head(n)

36
New cards

how do you print dataframe columns

print(df.columns)

37
New cards

does df.shape() display rows or columns first?

rows first then columns, seperated by comma.

38
New cards

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

)

39
New cards

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.

40
New cards

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)

41
New cards

how do you select a single column from a dataframe, how do you select multiple?

ages = df["Age"], subset = df[["Name", "Age"]]

42
New cards

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

43
New cards

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"]

44
New cards

what is the difference between = and ==?

= is used for defining variables, == is used as a comparison operator returning a true or false.

45
New cards

how would you sort age values in descending order in a dataframe?

sorted_df = df.sort_values(by="Age", ascending=False)

46
New cards

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.

47
New cards

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)

48
New cards

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()

49
New cards

what does df.describe() do?

summary statistics for all the numeric columns in a dataframe

50
New cards

how to import matplotlib?

import matplotlib.pyplot as plt

51
New cards

how do you create a line plot of temp vs time in matplotlib?

plt.plot(time, temperature)

52
New cards

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)

53
New cards

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()

54
New cards

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

55
New cards

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]

56
New cards

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.

57
New cards

how to plot using matplotlib to make a scatterplot with triangle markers of size 20?

plt.scatter(x, y, marker='^', s=20)

58
New cards

how to make bar chart and histogram in matplotlib

plt.bar(x,y), plt.hist(name, bins=20, edgecolor='black', color='steelblue')

59
New cards

how to add a legend

plt.legend(framealpha=0.9, fontsize=12, loc="upper left")

60
New cards

how to make second y axis

ax2 = ax1.twinx()

61
New cards

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.

62
New cards

how to import matplotlib

import matplotlib.pyplot as plt

63
New cards

how to make a grid in matplotlib of an alpha value of 0.3 with a dotted line

plt.grid(alpha=0.3, linestyle="--")

64
New cards

how to make an evenly spaced x-values for a matplotlib graph

np.linspace(x.min(), x.max(), 100)

65
New cards

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)

66
New cards

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.

67
New cards

what argument is used to put linear regression line above data point

zorder, zorder=2 is above zorder=1