Python Flashcards

1
Q

Dataframes: How to select all rows of a df where in col1 “Black” and “White” appear?

A

df[df[“col1”].isin([“Black”,”White”])]

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

Dataframes: How to select 2 columns?

A

df[[“col1”,”col2”]]

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

Dataframes: How to sort 2 columns of a df in descending order?

A

df.sort_values([“col1”,”col2”], ascending=[False, False])

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

Dataframes: How to get the values of a df?

A

df.values

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

Dataframes: How to get the description of a df?

A

df.describe()

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

Dataframes: How to get a shape of a df?

A

df.shape

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

Dataframes: How to get info about a df?

A

df.info()

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

Merging to the nearest date-times: How to replicate VLOOKUP(range_lookup=TRUE)?

A

pd.merge_asof(df1,df2,direction=”backward”) - direction:backward, forward, nearest

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

Advantage of pd.merge_ordered() vs. pd.merge?

A

pd.merge_ordered() has fill_method

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

Joining data: 2dfs (current, drafted) merged on column name and having the suffixes (‘_current’, ‘_drafted’) - how to sort the new df based on the column on which was merged?

A

current.merge(drafted, on=”name”, suffixes=(“_current”, “_drafted”), sort=True)

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

Joining data: Merge 2dfs (current, drafted) with an outer join and suffixes (‘_current’,’_drafted’) - how to show from which df a value is coming from?

A

current.merge(drafted, how=”outer”, on=”name”, suffixes=(“_current”,”_drafted”), indicator=True)

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

Joining data: Merging the df teams having the column player_id with df positions having player_id as index?

A

teams.merge(positions, left_on=”player_id”, right_index=True)

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

What are the joint default values for pd.merge and pd.merge_ordered?

A

pd.merge=inner join, pd.merge_ordered=outer join

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

Dataframes: How to use pd.merge_ordered with “ffill”?

A

pd.merge_ordered(df1, df2, on=”Date”, fill_method=”ffill”)

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

Dataframes: How to merge two dataframes with outer and sort index column called “Date”?

A

pd.merge(df1, df2, how=”outer”).sorted_values(“Date”)

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

Dataframes: How to join dataframes with integrated .join function with an inner join?

A

df1.join(df2, how=”inner”)

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

Dataframes: How to make an “inner” join with pd.merge on 2 columns and 2 suffixes?

A

pd.merge(df1, df2, on=[“col1”,”col2”], suffixes=[“_1”,”_2”], how=”inner”)

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

Dataframes: How to merge two dataframes on different columns in both dataframes?

A

pd.merge(df1,df2, left_on=”col1”, right_on=”col2”)

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

Dataframes: How to merge on several columns and/with using suffixes?

A

pd.merge(df1,df2,on=[“col1”,”col2”],suffixes=[“_1”,”_2”])

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

Dataframes: How to merge on several columns?

A

pd.merge(df1,df2,on=[“col1”,”col2”])

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

Dataframes: How to merge on one specific column?

A

pd.merge(df1,df2,on=”col1”)

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

Dataframes: What happens if pd.merge() is applied on 2 dataframes without any additional arguments?

A

computes a merge on all columns that occur in both dataframes, this is by default an “inner” join because it glues together only rows that match in the joining column of BOTH dataframes

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

Dataframes: Pandas: How to extend/ replace concat() with the ability to align rows using multiple columns?

A

pd.merge()

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

Dataframes: how to sort data by index?

A

df.sort_index()

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

Dataframes: How to use pd.concat to apply multi-indexing?

A

df_new=pd.concat([df1,df2],keys=[2020,2021],axis=0)

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

Dataframes: Print all rows that contain the name “Tom” in the column “name”

A

print(df.loc[df[“name”]==”Tom”])

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

Dataframe: When using .append: how to make a new RangeIndex of unique integers for each row?

A

df.total=df1.append(df2,ignore_index=True)

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

Concatenating rows: How to stack them horizontally?

A

pd.concat([df1,df2],axis=1)

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

Concatenating rows: How to stack them vertically?

A

pd.concat([df1,df2], axis=0)

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

Dataframes: How to get the name of an index?

A

df.index.name

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

Dataframes: How to use concat and reset index?

A

df_new=pd.concat([df1,df2], ignore_index=True)

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

Dataframes: How to use “append” with reset index?

A

df_new=df.append(df2).reset_index(drop=True)

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

Dataframes: How to replace all “F” with “C” in all column names in a df?

A

df_new.columns=df.columns.str.replace(“F”,”C”)

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

Dataframes: with .add(): how to add several dataframes with a fill_value=0?

A

bronze.add(silver,fill_value=0).add(gold,fill_value=0)

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

Dataframes: How to add one dataframe to another?

A

df1.add(df2)

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

Dataframe: How to add one dataframe to another and use 0 if value doesn’t exist?

A

df1.add(df2, fill_value=0)

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

Dataframes: how to calculate the percent changes?

A

df.pct_change()

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

Dataframes: How to divide one dataframe by another?

A

df.divide(df2, axis=”rows”)

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

Dataframes: How to use .loc for column “sales” for “Jan” to “Mar”?

A

df.loc[“Jan”:”Mar”,”sales”]

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

Dataframes: How to use .loc for the columns “Sales” and “Price” for “Jan” to “Mar”?

A

df.loc[“Jan”:”Mar”,[“Sales”,”Price”]]

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

Dataframes: if index is a date column how can the dates be parsed?

A

pd.read_csv(“sales.csv”, index_col=”Dates”, parse_dates=True)

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

Dataframes: When reindexing: time chaining method to replace the null values with the last preceding non-null value?

A

sales.reindex().ffill()

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

Dataframe: How to sort the index in reverse order?

A

df.sort_index(ascending=False)

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

Dataframes: How to sort the values in a column?

A

df.sort_values(“col1”)

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

Dataframes: how to drop rows with NA?

A

df.dropna()

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

What happens when a dataframe is reindexed with a missing label?

A

an empty row will be inserted

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

Reindex a dataframe with different dataframe?

A

df.reindex(df2.index)

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

How to sort the index of a dataframe?

A

df.sort_index()

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

Reindex dataframes: with first three months?

A

df=df.reindex([“Jan”,”Feb”,”Mar”])

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

Show index of a dataframe?

A

print(df.index)

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

With pd.read_csv: how to determine the index column?

A

index_col

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

Using a loop to append csv files into a dataframe?

A

filenames=[“df1.csv”,”df2.csv”], dataframes=[pd.read_csv(f) for f in filenames]

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

How to import csv files with * and glob?

A

from glob import glob, filenames=glob(“sales*.csv”), dataframes=[pd.read_csv(f) for f in filenames]

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

Dataframes: How to make an “outer” join with pd.concat and horizontally?

A

pd.concat([df1,df2], axis=1, join=”outer”)

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

Dataframes: How to make an “inner” join with pd.concat and horizontally?

A

pd.concat([df1,df2], axis=1, join=”inner”)

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

Pandas: How to sort by index values?

A

df.sort_index()

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

Directly on df: How to rotate x-axis by 45-degrees?

A

by putting “rot” into plot - df.plot(… rot=45), plt.show()

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

Directly on df: How to make a scatter plot?

A

df.plot(x=”column1”, y=”column2”, kind=”scatter”), plt.show()

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

Directly on df: How to add a legend?

A

plt.legend([“title1”,”title2”])

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

Directly on df: How to make a histogram partially transparent?

A

df.hist(…, alpha=0.7)

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

How to detect missing values with True and False in a df?

A

df.isna()

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

How to detect missing values with True and False in a df in any column=

A

df.isna().any()

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

How to count the missing values in a column?

A

df.isna().sum()

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

How to visualize in a boxplot the number of missing values in a dataframe?

A

df.isna().sum().plot(kind=”box”), plt.show()

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

How to remove rows with missing values in a df?

A

df.dropna()

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

How to fill NaN values in a df?

A

df.fillna()

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

Example of a very simple dictionary?

A

my_dict={“key1”:value1, “key2”:value2, “key3”:value3}

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

How to access the value of a dictionary?

A

my_dict[“key1”]

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

How to make a list of dictionaries by row and then put it into a dataframe?

A

list_of_dicts=[{“key1”:value1, “key2”:value2, “key3”:value3}, {“key1”:value4, “key2”:value5, “key3”:value6}] + pd.DataFrame(list_of_dicts)

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

How to make a dictionary of lists by column and then put it into a dataframe?

A

dict_of_lists={“key1”:[“value1”,”value2”], “key2”:[“value3”,”value4”], “key3”:[“value5”,”value6”]} + pd.DataFrame(dict_of_lists)

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

Directly on df: How to show a histogram with 20 bins?

A

df.plot(kind=”hist”, bins=20) + plt.show()

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

Directly on df: Bar plot with title?

A

df.plot(kind=”bar”, title=”irgendwas”) + plt.show()

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

Directly on df: How to make a line chart with x-axis based on a column and y-axis based on a different column?

A

df.plot(kind=”line”, x=”col1”, y=”col2”) + plt.show()

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

Direct on df: How to show a histogram?

A

df.plot(kind=”hist”) + plt.show()

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

Pandas: How to set a column as the index?

A

df=df.set_index(“col1”)

76
Q

Pandas: How to remove an index?

A

df.reset_index()

77
Q

Pandas: How to drop an index and delete the respective column?

A

df.reset_index(drop=True)

78
Q

Pandas: How to use .loc to get the same result: df[df[“col1”].isin([“name1”,”name2”])]?

A

df.loc[[“name1”,”name2”]]

79
Q

Pandas: How to use pivot_table with 0 instead of NaN for missing values and having the mean at the end of rows and columns?

A

df.pivot_table(values=”col1”, index=”col2”, columns=”col3”, fill_value=0, margins=True)

80
Q

How to transform df.groupby([“col1”,”col2”,”col3”]).mean() into a pivot_table?

A

df.pivot_table(values=”col1”, index=”col2”, columns=”col3”)

81
Q

Pandas: How to use multiple statistics with pivot_table?

A

df.pivot_table(values=”col1”, index=”col2”, aggfunc=[np.mean, np.median])

82
Q

Pandas: How to change df.groupby(“col1”)[“col2”].mean() into a pivot table?

A

df.pivot_table(values=”col2”, index=”col1”)

83
Q

Pandas: How to group by multiple variables?

A

df.groupby([“col1”,”col2”])[“col3”].mean()

84
Q

Pandas: How to get the min, max and sum for a column based on the characteristic of another column and groupby?

A

df.groupby(“col1”)[“col2”].agg([min,max,sum])

85
Q

Pandas: How to get the mean values of a column based on the characteristics of another column and groupby?

A

df.groupby(“col1”)[“col2”].mean()

86
Q

Pandas: How to show the proportionate amount of how often a value appears in a column?

A

df[“col1”].value_counts(normalize=True)

87
Q

Pandas: How to count the values in a column and have the highest values first?

A

df[“col1”].value_counts(sort=True)

88
Q

Pandas: How to count the values in a column?

A

df[“col1”].value_counts()

89
Q

Pandas: How to drop duplicates based on 2 columns?

A

unique=df.drop_duplicates(subset=[“col1”,”col2”])

90
Q

Pandas: How to drop duplicates base on a column?

A

df.drop_duplicates(subset=”col1”)

91
Q

Pandas: How to get the average of a column?

A

df[“col1”].mean()

92
Q

Pandas: How to get the variance of a column?

A

df[“col1”].var()

93
Q

Pandas: How to calculate the cumulative max?

A

df[“col1”].cummax()

94
Q

Pandas: How to calculate the cumulative sum?

A

df[“col1”].cumsum()

95
Q

Pandas: How to get the sum of a column?

A

df[“col1”].sum()

96
Q

Pandas: How to get the maximum value of a column?

A

df[“col1”].max()

97
Q

Pandas: How to merge 3 dfs at once? First two on col1 and then col2.

A

df.merge(df2, on=”col1”) \

.merge(df3, on=”col2”)

98
Q

Pandas: How to count the number of rows in col1 where something is missing?

A

df[“col1”].isnull().sum()

99
Q

Datetime: How to print/present a datetime object in a certain format?

A

datetime.datetime.strftime(“%Y-%m-%d”)

100
Q

Datetime: How to transform a string into a datetime format?

A

datetime.datetime.strptime(date_str, “%Y-%m-%d”)

101
Q

Datetime: How to calculate the difference between datetimes?

A

with timedelta

102
Q

Datetime: How to substract 1 week from datetime?

A

datetime.now() - timedelta(weeks = 1)

103
Q

Dictionaries: How to ask the value of a key and not getting an error message if the value doesn’t exist?

A

my_dict.get(“key1”)

104
Q

Dictionaries: How to ask the value of a key and getting a certain message if the value doesn’t exist?

A

my_dict.get(“key1”, “certain_message”)

105
Q

Dictionaries: How to delete a value from the dictionary?

A

del(my_dict[“key1”])

106
Q

Module to import data from Yahoo Finance?

A

yfinance

107
Q

yfinance: Download of SPY and AAPL?

A

data = yf.download(“SPY AAPL”, start=”2017-01-01”, end=”2017-04-30”)

108
Q

yfinance: Download of AAPL dividends?

A

apple= yf.Ticker(“aapl”), apple.dividends

109
Q

How to calculate log-returns for msft[‘Log_Ret’] based on msft[‘Close’]?

A

msft[‘Log_Ret’] = np.log(msft[‘Close’] / msft[‘Close’].shift(1))

110
Q

How to calculate volatility for msft[‘Volatility’] based on msft[‘Log_Ret’]?

A

msft[‘Volatility’] = msft[‘Log_Ret’].rolling(252).std() * np.sqrt(252)

111
Q

How plot the two columns msft[‘Close’] and msft[‘Volatility’] in two subplots but one graph and having for the lines the color blue and a figsize of 8,6?

A

msft[[‘Close’, ‘Volatility’]].plot(subplots=True, color=’blue’, figsize=(8, 6))

112
Q

How to time codes, i.e. how long it takes to execute them?

A

with %timeit or %%timeit

113
Q

Numpy: How to create a random standard normal variable?

A

np.random.standard_normal()

114
Q

Numpy: How to insert values based on values of another column?

A

np.where(sp500[‘42-252’] > SD, 1, 0)

115
Q

Backtesting a strategy: How to determine the backtest regime (sp500[‘Regime’]) based on column sp500[‘42-252’] and criteria SD?

A

sp500[‘Regime’]=np.where(sp500[‘42-252’] > SD, 1, 0)
sp500[‘Regime’]=np.where(sp500[‘42-252’] < -SD, -1, sp500[‘Regime’])
sp500[‘Regime’].value_counts()

116
Q

Backtesting a strategy: How to calculate the day to day return of the strategy in the column sp500[‘Strategy_Returns’] based on column sp500[‘Regime’] and sp500[‘Market_Returns’]?

A

sp500[‘Strategy_Returns’] = sp500[‘Regime’].shift(1) * sp500[‘Market_Returns’]

117
Q

Backtesting a strategy: How to plot the day to day returns of a strategy as well as the S&P as a cumulating sum based on the columns sp500[‘Strategy_Returns’] and sp500[‘Market_Returns’]? The graph should show grids and have a figsize of 8,5.

A

sp500[[‘Strategy_Returns’, ‘Market_Returns’]].cumsum().apply(np.exp).plot(grid=True, figsize=(8, 5))

118
Q

String objects: How to capitalize string s?

A

s.capitalize()

119
Q

String objects: How to split string s?

A

s.split()

120
Q

String objects: How to find a string (“string”) in the string s?

A

s.find(‘string’)

121
Q

String objects: How to count the number of occurrences of a substring in a string called s?

A

s.count(sub[, start[, end]])

122
Q

String: How to separate a list of words in a string called s with “,” as separator?

A

s.split(“,”)

123
Q

String: How to replace something in a string called s?

A

s.replace(old, new)

124
Q

Lists: How to replace the ith element by x in a list called l?

A

l[i]=x

125
Q

Lists: How to replace every kth element from i to j - 1 by s?

A

l[i:j:k] = s

126
Q

Lists: How to append the element x to the list object called l?

A

l.append(x)

127
Q

Lists: How to count the number of occurences of the element object x in the list object called l?

A

l.count(x)

128
Q

Lists: How to delete every kth elements in a list called l with index values i to j – 1?

A

del l[i:j:k]

129
Q

Lists: How to append all elements of s to an object called l?

A

l.extend(s)

130
Q

Lists: How to show the first index number of x between elements i and j - 1?

A

l.index(x[, i[, j]])

131
Q

Lists: How to insert x at/before index i into a list called l?

A

l.insert(i, x)

132
Q

Lists: How to remove the value at index i from a list called l?

A

l.remove(i)

133
Q

Lists: How to remove an element from a list called l with index i and return it?

A

l.pop(i)

134
Q

Lists: How to reverse all items in place in a list called l?

A

l.reverse()

135
Q

Lists: How to sort all items in place in a list called l?

A

l.sort()

136
Q

Dict: Item of d with k?

A

d[k]

137
Q

Dict: Setting item key k to x?

A

d[k]=x

138
Q

Dict: Deleting item with key k?

A

del d[k]

139
Q

Dict: Removing all items in d?

A

d.clear()

140
Q

Dict: How to make a copy of dict d?

A

d.copy()

141
Q

Dict: How to check if True if k is a key?

A

d.has_key(k)

142
Q

Dict: Copy of all key-value pairs of dict d?

A

d.items()

143
Q

Dict: Iterator over all items of dict d?

A

d.iteritems()

144
Q

Dict: Iterator over all keys of dict d?

A

d.iterkeys()

145
Q

Dict: Iterator over all values of dict d?

A

d.itervalues()

146
Q

Dict: Copy of all keys of dict d?

A

d.keys()

147
Q

Dict: How to return and remove item key k in dict d?

A

d.popitem(k)

148
Q

Dict: How to update items in d with items from d2?

A

d.update({d2})

149
Q

Dict: How to show all values of dictionary d?

A

d.values()

150
Q

Matplotlib: How to show grids?

A

plt.grid(True)

151
Q

plt.axis: How to turn axis and lines and labels off?

A

plt.axis(‘off’)

152
Q

plt.axis: How to make equal scaling?

A

plt.axis(‘equal’)

153
Q

plt.axis: How make equal scaling via dimension changes?

A

plt.axis(‘scaled’)

154
Q

plt.axis: How to make all data visible (tightens limits)?

A

plt.axis(‘tight’)

155
Q

plt.axis: How to make all data visible (with data limits)?

A

plt.axis(‘image’)

156
Q

plt.axis: How to determine minimum and maximum values of x and y?

A

xmin, xmax, ymin, ymax or ylim and xlim

157
Q

matplotlib: How to determine title of a graph?

A

plt.title()

158
Q

Matplotlib: How to determine x and y labels?

A

plt.xlabel and plt.ylabel

159
Q

Matplotlib: How make a graph with data y and with red circles?

A

plt.plot(y, ‘ro’)

160
Q

Matplotlib: How to position the legend?

A

plt.legend(loc=0)

161
Q

Matplotlib: How to make a second y-axis?

A

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

162
Q

Matplotlib: How to address a subplot?

A

plt.subplot(numrows, numcols, fignum)

163
Q

Matplotlib: How to plot two values in a Histogram with data y(having two columns), with the labels “1st” and “2nd” and 25 bins next to each other?

A

plt.hist(y, label=[‘1st’,’2nd’], bins=25)

164
Q

Show the index of a dataframe?

A

df.index

165
Q

Show the columns of a dataframe?

A

df.columns

166
Q

Pandas: creating a DatetimeIndex object for 1.1.2015 with frequency months and occurence 9 times?

A

pd.date_range(‘2015-1-1’, periods=9, freq=’M’)

167
Q

Python module to import data via URL?

A

from urllib.request import urlretrieve

168
Q

How to use urlretrieve to save a txt file from the web locally?

A

url=’https://www.stoxx.com/document/Indices/Current/HistoricalData/h_vstoxx.txt’
urlretrieve(url, ‘./data/vstoxx.txt’)

169
Q

How to remove all blanks in a txt file?

A

lines=open(‘./data/vstoxx.txt’, ‘r’).readlines()

lines=[line.replace(‘ ‘,’’) for line in lines]

170
Q

How to fill in a dataframe the NA values with the last available values from the data series?

A

data.fillna(method=’ffill’)

171
Q

How to make a regression with xdat and ydat?

A

pd.ols(y=ydat, x=xdat)

172
Q

How to calculate the correlation between two variables in df “rets” having the columns .SPX and .VIX?

A

rets.corr()

173
Q

How to import a csv file (data.csv) and read all lines?

A

csv_file=open(path + ‘data.csv’ + ‘r’)

content = csv_file.readlines()

174
Q

How to use the arange function of NumPy to generate minutes data from 2020-01-01 10:00:00 to 2020-12-31 10:00:00)?

A

np.arange(‘2020-01-01 10:00:00’, ‘2020-12-31 10:00:00’, dtype=’datetime64[m]’)

175
Q

How to turn the grid on in a graph?

A

plt.grid(True)

176
Q

How to create 10 random numbers?

A

[random.random() for _ in range(10)]

177
Q

How to create 10 random numbers between 1 and 5?

A

[random.randint(1,5) for _ in range(10)]

178
Q

How to make a random amount of letters of the alphabet and then count which letter occurs how many times?

A
import random
import string
lc=string.ascii_lowercase
rc=[random.choice(lc) for _ in range(10000)]
c={c:rc.count(c) for c in lc}
179
Q

Pandas: How to copy/insert a website into a variable?

A

pd.read_html(url)

180
Q

If share price is in df data: how to normalize the share price and plot it in a 8,6 figsize?

A

(data/data.ix[0]*100).plot(figsize=(8, 6))

181
Q

If share price is in df data: How to calculate log-returns?

A

np.log(data/ data.shift(1))

182
Q

How to calculate from a df of daily log-returns a covariance matrix?

A

rets.cov()*252

183
Q

How to make a colorbar for a scatter plot with the label “Sharpe ratio”?

A

plt.colorbar(label=’Sharpe ratio’)

184
Q

Pandas: How to read data from an Excel file from a workbook called “workbook.xlsx” and sheet called “first_sheet”?

A

df=pd.read_excel(path + ‘workbook.xlsx’, ‘first_sheet’, header=None)

185
Q

Pandas: How to write a df into an Excel sheet called “new_book_1.xlsx” and into “my_sheet”?

A

df.to_excel(path + “new_book_1.xlsx”, “my_sheet”)

186
Q

How to import matplotlib module?

A

import matplotlib.pyplot as plt

187
Q

How to create figure and axis object in matplotlib?

A

fig, ax = plt.subplots()