Section 1

Preview this deck

add new column to DataFrame

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (54)

Section 1

(50 cards)

add new column to DataFrame

Front

df['new'] = df['A'] + df['B']

Back

np.random.randn(x)

Front

generate an array of x random numbers sampled from a standard normal distribution

Back

pop() Function

Front

removes value from dictionary names.pop(Key)

Back

np.zeros(x) and np.ones(x)

Front

creates array of x amount of 0s or 1s

Back

to_csv()

Front

write to csv file ex: df.to_csv('myOutput', index=False)

Back

Examples of plot() variables

Front

color='#FF8C00' linewidth=3 alpha=0.5 linestyle=':' marker='o' markersize=10 markerfacecolor='green' markeredgewidth=3 markeredgecolor='blue'

Back

Pandas

Front

used for series and data frames. ex: import pandas as pd

Back

plt.subplots()

Front

creates multiple graphs on one canvas ex: fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8,2)) axes[0].plot(x,y) axes[1].plot(y,x) plt.tight_layout()

Back

np.arange

Front

np.arange(10,51,2) array([10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]) loop example: for i in range(3): print(i)

Back

groupby()

Front

groups identical values in DataFrame ex: byGroup = df.groupby('Group') byGroup.sum() or df.groupby('Group').sum()

Back

keys()

Front

Prints all keys in dictionary dict.keys()

Back

eye()

Front

Identity Matrix ex: np.eye(3,3) ([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])

Back

Logarithmic Return

Front

log(closing price/previous closing price) ex: PG['log return'] = np.log(PG['Adj Close']/PG['Adj Close'].shift(1))

Back

formatted strings

Front

print (f"This adds {variable} into string")

Back

np.random.rand()

Front

generates a pseudo-random number; if no argument given, returns a float between zero and one

Back

Dictionary syntax

Front

names = {Key1: Value1, Key2: Value2, ...} names[Key1] ##Lookup or Change Keys and Values can be of any type.

Back

np.linspace(x, y, z)

Front

creates z evenly spaced numbers starting with x and ending in y

Back

Series

Front

import pandas as pd pd.Series[data, index]

Back

pandas_datareader

Front

from pandas_datareader import data as web import datetime start = datetime.datetime(2015, 1, 1) end = datetime.datetime(2017, 1, 1) stock = web.DataReader('FB', 'av-daily', start, end, api_key=('1HTZ1QTQW0NQN2LS'))

Back

savefig()

Front

save graph to file ex: fig.savefig('my_picture.png', dpi=200)

Back

pd.read_excel()

Front

read from excel file ex: pd.read_excel('excelFile.xlsx', sheetname='Sheet1')

Back

Annual Rate of Return

Front

# mean of simple returns * 250 days returns = (mydata/mydata.shift(1)) - 1 annual_returns = returns.mean()*250

Back

search multiple conditions in DataFrames

Front

ex: df[ (df['A'] > 0) & (df['B'] > 1) ] :AND df[ (df['A'] > 0) | (df['B'] > 1) ] :OR

Back

fillna()

Front

fills NaN value in DataFrame with another value ex: df.fillna(value='Fill Value') df['A'].fillna(value=df['A'].mean())

Back

unique() and nunique()

Front

returns unique values in DataFrame ex: df['col1'].unique() // returns array of unique values df['col1'].nunique() // returns number of unique values

Back

DataFrame Syntax

Front

import pandas as pd df = pd.DataFrame(array, index=['A','B'], columns=['One','Two','Three'])

Back

join()

Front

joins DataFrames off indexes // use merge to "join" using column indexes ex: df1.join(df2)

Back

NumPy

Front

a scientific computing python package for Arrays and Matrixes import numpy as np

Back

matplotlib basic graph code

Front

fig = plt.figure() axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) axes.plot(x, y) axes.set_xlabel('X Label') axes.set_ylabel('Y Label') axes.set_title('This is my graph')

Back

Simple Rate of Return

Front

(closing price/previous closing price) - 1 ex: PG['simple return'] = (PG['Adj Close']/PG['Adj Close'].shift(1))-1

Back

for loop syntax

Front

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)

Back

pd.merge()

Front

merges DataFrames with identical keys ex: pd.merge(df1, df2, how='inner', on='key')

Back

value.counts()

Front

returns values and number of times they are in a DataFrame column ex: df['col2'].value_counts()

Back

apply()

Front

apply a function to DataFrame ex: df['col2'].apply(len) ///returns series df['col2'].apply(lamda x: x*2) /// applies user function

Back

sort_values()

Front

sorts DataFrame ex: df.sort_values('col2')

Back

matplotlib import code

Front

import matplotlib.pyplot as plt %matplotlib inline ///allows plotting within notebook %matplotlib notebook ///allows interaction

Back

Working with Lists

Front

list.append('value') // Adds to end list.insert(index, 'value') // Adds del list[index] // Deletes by index list.remove('value') // Removes by value pop_list= list.pop() //Removes last value and reassigns

Back

while loop syntax

Front

price = 4 while price > 0: print(price) price = price - 1 can use break to exit

Back

Python Functions

Front

ex: def functionName(values): .... return x

Back

remove column/row from DataFrame

Front

COLUMN: df.drop('new', axis = 1, inplace = True) ROW: df.drop('new', axis = 0, inplace = True) inplace will remove for good from source

Back

datetime

Front

from datatime import datetime ex: myDateTime = datetime(year, month, day, hour, min, sec)

Back

locate in DataFrame

Front

df['Column Name'] df.loc['Row Name'] df.iloc[row index] df.loc['Row Name', 'Column Name']

Back

dropna()

Front

used to drop row/column from DataFrame with NaN value ex: df.dropna() //row df.dropna(axis=1) // column (thresh) = number of NaN required to remove

Back

reshape()

Front

creates or reshapes matrix x = np.arange(0,9) x.reshape(3,3) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

Back

Normalization to 100

Front

ex: (mydata/mydata.iloc[0]*100).plot(figsize=(15,6)); plt.show

Back

update() Function

Front

overwrites multiple values in dictionary names.update({Key1: newValue1, Key2: newValue2, ...})

Back

drop()

Front

drops row/column from DataFrame ex: df.drop('col1', axis=1, inplace=true) df.drop('row1', axis=0)

Back

set_index()

Front

set index in DataFrame df.set_index('Column', inplace = true) will overwrite current index column

Back

pd.read_csv()

Front

read from csv file ex: df = pd.read_csv('example.csv')

Back

pd.concat()

Front

glues DataFrames together ex: pd.concat([df1, df2, df3])

Back

Section 2

(4 cards)

tuple

Front

can store a collection like a [list] but cannot assign new values to individual elements. Uses ( ) ex: thisTuple = (1, 2, 3, 4)

Back

json

Front

import json with open(filename, 'w') as f: json.dump(list, f) ///add to json list = json.load(f) ///pull from json

Back

get( )

Front

used to get values from dictionary with the bonus of allowing a default result if it is not. ex: mydict.get('key', 'value if not found')

Back

range()

Front

ex: range(startNum, endNum, Interval)

Back