Bloomberg DMP Flashcards

(236 cards)

1
Q

How would I get the documentation for a specific function?

A

help(func_name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do I write documentation in python code?

A

# this is a comment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How would I see what is the type of an object?

A

type(‘a’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How would i install pandas manually?

A

pip install pandas

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do I import pandas without an alias?

A

import pandas

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do I import pandas with an alias?

A

import pandas as pd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do I import an object from a package?

A

from pandas import DataFrame

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How would I import the operating system package?

A

import os

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do I get the current directory?

A

os.getcwd()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do I set the working directory to a new file path?

A

os.setcwd(“new/working/directory”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What do I use to add two numbers?

A

+

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What do i use to subtract two numbers?

A

-

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What do I use to multiply two numbers?

A

*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do I use to divide a number by another number?

A

/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do I integer divide?

A

//

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do I raise a number to a power?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do I get the remainder after division?

A

%

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do I assign a value to a?

A

a = 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do I change the value of an item in a list?

A

x[0] = 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do I compare equality?

A

==

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do I test for inequality?

A

!=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do I test for greater than?

A

>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do I test for greater than or equal to?

A

> =

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do I test for less than or equal to?

A

<=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do I test for less than?
<
26
What are the three logical operators?
not, and, or
27
How do I create a list with integers 1, 3, and 2?
x = [1, 3, 2]
28
How do i return a sorted copy of a list?
x.sorted(x)
29
What does x.sorted(x) return?
a copy of a list, in sorted order
30
How do we sort a list in place?
x.sort()
31
How do we reverse the order of elements in a list?
reversed(x)
32
How do we reverse a list in place?
x.reversed()
33
How do we count the number of element 2 in a list?
x.count(2)
34
What do ranges of list include?
the first element is included but the last is not
35
What does x[0] return?
the first element of a list
36
What does x[-1] return?
the last element of a list
37
What does x[1:3] return?
all the elements from 1 (inclusive) to the 3rd (exclusive)
38
What does x[2:] return?
from the second element to the end
39
What does x[:3] return?
from the 0th to the 3rd element (exclusive)
40
If we have a list x = [1, 3, 6] and y = [10, 15, 21], what does x + y return?
[1, 3, 6, 10, 15, 21]
41
If we have a list x = [1, 3, 6], what does 3 * x return?
[1, 3, 6, 1, 3, 6, 1, 3, 6]
42
How do we create a dictionary?
using {}
43
If we have a dictionary called x = {'a': 1, 'b': 2, 'c': 3}, what does x.keys() return?
dict_keys(['a', 'b', 'c'])
44
If we have a dictionary called x = {'a': 1, 'b': 2, 'c': 3}, what does x.values() return?
dict_values([1, 2, 3])
45
How do we select dictionary elements?
x['a'] where 'a' is the key and the value is returned
46
How do we import NumPy?
import numpy as np
47
How do we convert a python list to a NumPy array?
np.array([1, 2, 3])
48
What does np.array([1, 2, 3]) return?
array([1, 2, 3])
49
What does np.arange(1, 5) return?
array([1, 2, 3, 4])
50
What does np.repeat([1, 3, 6], 3) return?
array([1, 1, 1, 3, 3, 3, 6, 6, 6])
51
What does np.tile([1, 3, 6], 3) return?
array([1, 3, 6, 1, 3, 6, 1, 3, 6])
52
How do we calculate the logarithm?
np.log(x)
53
How do we calculate an exponential?
np.exp(x)
54
How do we get the maximum value?
np.max(x)
55
How do we get the minimum value?
np.min()
56
How do we calculate the sum?
np.sum(x)
57
How do we calculate the mean?
np.mean(x)
58
How do we get the q-th quantile?
np.quantile(x, q)
59
How do we round to n decimal places?
np.round(x, n)
60
How do we calculate the variance?
np.var(x)
61
How do we calculate the standard deviation?
np.std(x)
62
What do all the numpy functions take as input?
arrays
63
How do we embed a quote in a string with an escape character?
"He said, \"DataCamp\""
64
How do we create a multi-line string?
using triple quotes like: """ TO ADD COMMENT HERE. """
65
What does "Data" + "Framed" return?
'DataFramed'
66
How do we repeat strings using *?
3 * "data " would come out to 'data data data '
67
How ca we split a string on a delimiter?
"beekepers".split("e")
68
What does "beekepers".split("e") return?
['b', '', 'k', '', 'p', 'rs']
69
How do we convert a string to an uppercase if we named it str?
str.upper()
70
How do we convert a string to an lowercase if we named it str?
str.lower()
71
How do we convert a string to a title case if we named it str?
str.title()
72
How do we replace matches of a substring with another?
str.replace("J", "P") where J is being replaced with P
73
How do we create a dataframe from a dictionary?
pd.DataFrame({ 'a': [1, 2, 3], 'b': np.array([4, 4, 6]), 'c': ['x', 'x', 'y'] })
74
How do we create a dataframe from a list of dictionaries?
pd.DataFrame([ {'a': 1, 'b': 4, 'c': 'x'}, {'a': 1, 'b': 4, 'c': 'x'}, {'a': 3, 'b': 6, 'c': 'y'} ])
75
How would we select the third row of a dataframe?
df.iloc[3]
76
How would we select one column by name of a df?
df['col']
77
How would we select multiple columns by names of a df?
df[['col1', 'col2']]
78
How would we select the second column of a dataframe?
df.iloc[:, 2]
79
How would we select the element in the 3rd row, 2nd column of a df?
df.iloc[3, 2]
80
How would we concatenate two dataframes vertically?
pd.concat([df, df2])
81
How do we concatenate two dataframes horizontally?
pd.concat([df, df2], axis="columns")
82
How would we get rows matching a condition?
either df[df['col'] == 'condition'] or df.query('logical_condition')
83
How do we drop a dataframe's columns by name?
df.drop(columns=['col_name'])
84
How do we rename a dataframes columns?
df.rename(columns={"oldname": "newname"})
85
How do we add a new dataframe column?
df.assign(temp_f=9 / 5 * df['temp_c'] + 32)
86
How do we calculate the mean of each column in a dataframe?
df.mean()
87
How do we get the summary statistics by column of a dataframe?
df.agg(aggregation_function)
88
How do we get unique rows of a dataframe?
df.drop_duplicates()
89
How do we sort by values in a column?
df.sort_values(by='col_name')
90
How do we get the rows with largest values in a column of a dataframe?
df.nlargest(n, 'col_name')
91
What does x ** 2 mean?
x is being raised to the power of 2
92
What does str() do?
we can use it to turn variables to strings, it is a type conversion
93
What does int() do?
it turns variables to integers, it is a type conversion
94
What does float() do?
it turns variables to floats, it is a type conversion
95
What does bool() do?
it turns variables to booleans, it is a type conversion
96
What is the main library for data analysis?
pandas
97
What is the main library for scientific computing?
NumPy
98
What is the main library for 2D plotting?
matplotlib
99
What is the main library for machine learning?
sci-kit learn
100
What does 'm' in my_string return?
a boolean value, true if 'm' is within my_string and false otherwise
101
What does my_string.count('w') do?
it counts the number of string elements
102
How do we strip whitespaces of a string?
my_string.strip()
103
If we have a 2D array, how do we use slicing?
my_2darray[rows, columns]
104
If I have an array, what would my_array > 3 return?
an array of true and falses like array([2, 4, 6, 8])
105
How would I multiple every single integer of an array by two?
my_array * 2
106
What does adding .shape at the end of an array show us?
the dimensions of the array
107
How do we append items to an array?
np.append(other_array)
108
How do we insert items into an array with numpy?
np.insert(my_array, 1, 5)
109
How do I delete items in an array with numpy?
np.delete(my_array, [1])
110
How do I get the mean of an array with numpy?
np.mean(my_array)
111
How do I get the median of an array with numpy?
np.median(my_array)
112
How do I get the correlation coefficient of a numpy array?
my_array.corrcoef()
113
How do I get the standard deviation of an array using numpy?
np.std(my_array)
114
How would I copy my_list using slicing?
my_list[:]
115
How do we get the index of an item of a list?
my_list(a)
116
How do we append an item at a time of a list?
my_list.append('!')
117
How do we remove an item of a list?
del(my_list[0:1])
118
How do we reverse a list?
my_list.reverse()
119
What is another way to append an item to a list?
my_list.extend('!')
120
How do we pop an item of a list?
my_list.pop(-1)
121
How do we insert an item at a specific index of a list?
my_list.insert(0, '!')
122
How do we sort a list?
my_list.sort()
123
How do we save a plain text file using python?
filename = 'huck_finn.txt'
124
How do we open a file for reading using python?
file = open(filename, mode='r')
125
How do we read the file's context using the previous file we opened?
text = file.read()
126
How do we check if a file is closed using python?
print(file.closed)
127
How do we close a file using python?
file.close()
128
How would we print the text that we read in from a file using python?
print(text)
129
How do we open a file and read it at the same time in using python?
with open('huck_finn.txt', 'r') as file: print(file.readline()) print(file.readline()) print(file.readline())
130
How do we import flat files with one data type using numpy?
filename = 'mnist.txt' data = np.loadtxt(filename, delimiter=',', skiprows=2, usecols=[0,2], dtype=str)
131
What does the skiprows argument in .loadtxt() mean?
it allows us to skip the first n lines
132
What does the delimiter argument in .loadtxt() mean?
the string we will be using to separate values
133
How do we import flat files with mixed data types using numpy?
filename = 'titanic.csv' data = np.genfromtxt(filename, delimiter=', ', names=True, dtype=None)
134
How do we import flat files with pandas?
filename = 'winequality-red.csv' data = pd.read_csv(filename, nrows=5, header=None, sep='\t', comment='#', na_values=[""])
135
How would we check the data type of array elements using numpy?
array.dtype
136
How do we get the length of an array using numpy?
len(array)
137
How do we return first DataFrame rows using pandas?
df.head()
138
How do we return last DataFrame rows using pandas?
df.tail()
139
How do we describe the index using pandas?
df.index
140
How do we get the columns of a dataframe using pandas?
df.columns
141
How do we get info on a dataframe using pandas?
df.info()
142
How do we convert a DataFrame to a NumPy array?
data_array = data.values
143
How do we import a SAS file?
from sas7bdat import SAS7BDAT with SAS7BDAT('urbanpop.sas7bdat') as file: df_sas = file.to_data_frame()
144
How do we read in a stata file?
data = pd.read_stata('ubranpop.dta')
145
How do we read in excel spreadsheets?
file = 'urbanpop.xlsx' data = pd.ExcelFile(file) df_sheet2 = data.parse('1960-1966', skiprows=[0], names=['Country', 'AAM: War(2002)'])
146
How do we access the sheet names?
data.sheet_names attribute
147
How would we create an engine?
from sqlalchemy import create_engine engine = create_engine('sqlite://Northwind.sqlite')
148
How would we fetch a list of table names?
table_names = engine.table_names()
149
How do we query using a relational database?
con = engine.connect() rs = con.exectue("SELECT * FROM Orders") df = pd.DataFrame(rs.fetchall()) df.columns = rs.keys() con.close()
150
How would we query into a relational database using context manager?
with engine.connect() as con: rs = con.execute("SELECT OrderID FROM Orders") df = pd.DataFrame(rs.fetchmany(size=5)) df.columns = rs.keys()
151
How do we query relational databases with pandas?
df= pd.read_sql_query("SELECT * FROM Orders", engine)
152
How do we read in pickled files?
import pickle with open('pickled_fruit.pkl', 'rb') as file: pickled_data = pickle.load(file)
153
How do we read in matlab files?
import scipy.io filename = 'workspace.mat' mat = scipy.io.loadmat(filename)
154
How do we import HDF5 files?
import h5py filename = 'H-H1_LOSC_4_v18154112004096.hdf5' data = h5py.File(filename, 'r')
155
How would we print dictionary keys?
print(mat.keys())
156
How would we use a for loop to print dictionary keys?
for key in data.keys(): print(key)
157
What is !ls?
list directory contents of files and directories
158
What is %cd?
change current working directory
159
What is %pwd?
return the current working directory path
160
What is a date?
handles dates without time
161
What is POSIXct?
handles date and time in calendar time
162
What is POSIXIt?
handles date and time in local time
163
What is Hms?
parses periods with hour, minute, and second
164
What is a timestamp?
represents a single pandas date and time
165
What is an interval?
defines an open or closed range between dates and times
166
What is time delta?
computes time difference between different datetimes
167
What is the ISO 8601 datetime format?
YYYY-MM-DD HH:MM:SS TZ
168
What does the ISO 8601 datetime format avoid?
ambiguities between MM/DD/YYYY and DD/MM/YYYY
169
What does ISO 8601 mitigate?
overflow problems after the year 2099
170
What language is optimized for the ISO 8601 datetime format?
python
171
What packages do we need to import to use datetime and time?
import datetime as dt import time as tm import pytz
172
How do we get the current date?
dt.date.today()
173
How do we get the current date and time?
dt.datetime.now()
174
How do we specify a datetime column?
pd.read_csv('filename.csv', parse_dates = ["col_1", "col_2"])
175
How do we specify a datetime column?
pd.read_csv("filename.csv", parse_dates = {"col1": ["year", "month", "day"]})
176
How would we parse dates in ISO format?
pd.to_datetime(iso)
177
How would we parse dates in US format?
pd.to_datetime(us, dayfirst=False)
178
How would we parse dates in non US format?
pd.to_datetime(non_us, dayfirst=True)
179
How would we parse dates, guessing a single format?
pd.to_datetime(iso, infer_datetime_format=True)
180
How would we parse dates in a single, specified format?
pd.to_datetime(iso, format="%Y-%m-%d %H:%M:%S") or pd.to_datetime(us, format="%m/%d%Y %H:%M:%S")
181
How would we make dates from components?
pd.to_datetime(parts)
182
How would we parse strings to datetimes?
dttm = pd.to_datetime(iso)
183
How do we get year from a datetime pandas series?
dttm.dt.year
184
How do we get day of the year from a datetime pandas series?
dttm.dt.day_of_year
185
How do we get month from a datetime pandas series?
dttm.dt.month_name()
186
How do we get day name from datetime pandas series?
dttm.dt.day_name()
187
How do we get datetime.datetime format from a datetime pandas series?
dttm.dt.to_pydatetime()
188
How do we round dates to nearest time unit?
dttm.dt.round('1min')
189
How do we floor dates to nearest time unit?
dttm.dt.floor('1min')
190
How do we ceiling dates to nearest time unit?
dttm.dt.ceil('1min')
191
How do we create two datetimes?
now = dt.datetime.now() then = pd.Timestamp('2021-09-15 10:03:30')
192
How would we get time elapsed between two datetimes as timedelta object?
now - then
193
How would we get time elapsed in seconds between two datetimes?
(now - then).total_seconds()
194
How would we add a day to a datetime?
dt.datetime(2022, 8, 5, 11, 13, 50) + dt.timedelta(days=1)
195
How do we get the current time zone?
tm.localtime().tm_zone
196
How do we get a list of all time zones?
pytz.all_timezones
197
How do we get datetime with timezone using location?
dttm.dt.tz_localize('CET', amigguous='infer')
198
How do we get datetime with timezone using UTC offset?
dttm.dt.tz_localize('+0100')
199
How do we convert datetime from one timezone to another?
dttm.dt.tz_localize('+0100').tz_convert('US/Central')
200
How do we get the length of a time interval between two datetimes?
pd.Interval(start_1, finish_1, closed='right').length
201
How do we determine if two intervals are intersecting?
pd.Interval(start_1, finish_1, closed='right').overlaps(pd.Interval(start_2, finish_2, closed='right'))
202
How do we define a timedelta in days?
pd.Timedelta(7, "d")
203
How do we convert timedelta to seconds?
pd.Timedelta(7, "d").total_seconds()
204
How do we get the number of characters with string length of a series?
seriesName.str.len()
205
How do we get substrings by position?
seriesName.str[2:5]
206
How do we get substrings by negative postion?
seriesName.str[:-3]
207
How do we pad strings of a series given a length with .str.pad()?
seriesName.str.pad(8, fillchar="_")
208
How do we remove whitespace of a series from the start/end?
seriesName.str.strip()
209
How do we convert a series to lowercase?
seriesName.str.lower()
210
How do we convert a series to title case?
pd.Series("hello, world!").str.title()
211
How do we convert a series to uppercase?
seriesName.str.upper()
212
How do we convert a series to sentence case?
pd.Series("hello, world!").str.capitalize()
213
How do we split strings into a list of characters?
suits.str.split(pat="")
214
How do we split strings by a separator?
suits.str.split(pat = "a")
215
How do we split strings and return a DataFrame?
suits.str.split(pat = "a", expand=True)
216
How do we detect if a regex pattern is present in a string?
suits.str.contains("[ae]")
217
How do we count the number of matches with .str.count()?
sutis.str.count("[ae]")
218
How do we locate the positon of substrings with str.find()?
suits.str.find("e")
219
How do we extract matches from strings?
suits.str.findall(".[ae]")
220
How do we extract capture groups?
suits.str.extractall("([ae])(.)")
221
How do we get a subset of strings that match?
suits[suits.str.contains("d")]
222
How do we replace a regex match with another string?
suits.str.replace("a", "4")
223
How do we remove a suffix?
suits.str.removesuffix
224
How do we replace a substring?
rhymes.str.slice_replace(0, 1, "r")
225
What is a series?
a one-dimensional labeled array capable of holding any data type
226
What is a dataframe?
a two-dimensional labeled data structure with columns of potentially different types
227
How do we drop values from rows?
s.drop(['a', 'c'])
228
How do we sort by labels along an axis?
df.sort_index()
229
How do we sort by values along an axis?
df.sort_values(by='Country')
230
How do we assign ranks to entries?
df.rank()
231
How do we read read a csv?
pd.read_csv('file.csv', header=None, nrows=5)
232
How do we write a csv?
df.to_csv('myDataFrame.csv')
233
How do we read excel?
pd.read_excel('file.xlsx')
234
How do we write to excel?
df.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1')
235
How do we read multiple sheets from the same file?
xlsx = pd.ExcelFile('file.xls')
236