Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

PYTHON 3

INT/FLOAT OPERATORS 3 + 2.56 DICT. OPERATORS {ky1: “A”, ky2: list}


int(“25“) > String to integer dic[key] = val > Add a key
CHEET SHEET BY @CHARLSTOWN
type() > Returns type dic.update({ky: v, ky: v}) > Add multiple keys
A//B > Returns ratio dic[key] = val > Overwrites value
CREATOR: GUIDO VAN ROSSUM A&B > Returns reminder dic[key] > Extracts a value I
YEAR: 1991 divmod(A, B) > Ratio/reminder dic.get(key) > Extracts a value II
LATEST VERSION (2019): 3.7.4 len() > Returns lenght dic.get(key, DefVal) > Extracts a value III
TOP LIBRARIES: TENSORFLOW, SCIKIT-LEARN, max() > Max. value dic.pop(key) > Delete K and V I
NUMPY, KERAS, PYTORCH, PANDAS, SCIPY min() > Min. value del dic[k] > Delete K and V II
abs() > Absolute value dic.keys() > Keys List
ELEMENTAL LIBRARIES import * pow(5, 2) > 5 powered by 2 dic.values() > Values list
import lib > Import all from lib 5**2 > 5 powered by 2 dic.items() > Returns K and V
from lib import function > Import function I round(A, 3) > Round 3 decimals key in dict > Checks key
lib.function() > Import function II sum(list) > Sum all list items dict(zip(lst_1, lst_2)) > Pair lists to Dict.
dir(math) > Show all functions LOOPS LIST & DICT COMPREHENSIONS
import library as lb >Library shortcut
for item in list: > for loop LIST COMPREHENSION
STRING OPERATORS “Hello world” print(item) > Iterate by items lst_A = [i for i in lst_B if i < 0]
str(29) > Int/Float to string LIST COMPREHENSION NESTED
len(“string”) > Total string length while limit <= 5 : > while loop
lst_A = [i if i < 0 else i-5 for i in lst_B]
“My” + “age is:” + “28” > Sum strings limit += 1 > Iterate by condition
“Hey!” * 3 > Repeat string by 3 LIST COMPREHENSION NESTED
LIST OPERATORS [“A”, “B”, 5, True]
“a“ in “chartlstown“ > True if str in str lst_A = [[i+1 for i in x] for x in lst_B]
‘letters‘.isalpha() > Check only letters len(list) > Count items in list
‘string’.upper() > STR to CAPS-CASE list(range(0,10,2)) > List from range DICT COMPREHENSION
‘string‘.lower() > STR to lower-case list.reverse() > Reverse the list {key: value for key, value in dict.items()}
‘string‘.title() > First letter to CAPS lst[idx] > Element index FUNCTION & LAMBDA:
list(“string“) > Letters to list lst[idx] = “item” > Change item
‘my string‘.split() > Words to List lst.append(‘item’) > Add item def switch(in1, in 2): > Code as function
““.join(list) > List to String by ““ lst[-5:] > Slicing list return (in2, in1) > Switch variables
“AB“.replace(“A”, “B”) > Replace AB > BB list.index(“B”) > Position index switch(“a”, “b”) > Run function on a,b
string.find(“A”) > Index from match list.insert(0, A) > Insert item by index
“ A “.strip() > No leading spaces list.remove(5) > Remove element plus_one = lambda x: x+1 > Code as expression
f”My age: {28}” > Insert in string list.count(A) > A frequency plus_one(5) > Number plus 1
“”My age: {}”.format(28) > Old insert in string list.sort() > Sort in same list
“AB\”CD” > Include symbol “ sorted(lst) > Sort in new list TIMING THE CODE
“\n” > New line in string lst.pop() > Last item time.time() > Get elapsed time
“\t” > Tabulator in string list(zip(lst_1, lst_2)) > Entwine pair of lists time.sleep(s) > Pause code s secs.
var = input(‘question?’) >Input string form enumerate(list) > Add index to list time.localtime() > Get local time
NUMPY_LIBRARY PANDAS_LIBRARY PANDAS AGGREGATES (COMANDS)
BASIC FUNCTIONS import numpy as np DATA FRAMES import pandas as pd df.c1.unique() >> Extracts the set
IMPORTING CSV FILES: IMPORTING CSV FILES: df.c1.nunique() >> Extracts len(set)
np.getfromtxt(‘f.csv’, delimiter = ‘,’) pd.read_csv(‘f.csv’) df.c1.mean() >> Average of the column
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - df.c1.median() >> Median of the column
np.mean(lst) >> Average pd.DataFrame(Dict) >> Create a DF I df.c1.std() >> Standard deviation
np.sort(lst) >> Sort the list columns = [list] >> Create a DF II df.c1.max() >> Max number
np.median(lst) >> Median - - - - - - - - - - - - - - - - - - - - df.c1.min() >> Min number
np.percentile(lst, n) >> Percentil n% df.head(n) >> shows first n rows df.c1.count() >> len of the set
np.std(lst) >> Standard devi. df.info() >> entries and data P.A. (GROOPING)
np.mean(mtx < n) >> Conditions
np.var() >> Variance EXTRACTING COLUMNS AND ROWS df.groupby(c1).c2.mean()* >> Groups c1
df.column.values >> Extract column df.groupby(c1).id.count()* >> Counter
MATRIX import numpy as np df.groupby(c1).c2.apply(lb)* >> lambda
df[‘colum’] >> Extract multiple clmns
mtx = np.array(lst1, lst2, lst3) df[[c1, c2]] >> Extracts columns as df df.groupby([c1,c2]).c3* >> Multiple g
np.mean(mtx) >>Total data mean df.iloc[index] >> Extracts the Row by idx * > .reset_index() >> To reset df
np.mean(mtx, axis = 0) >> Columns mean df.iloc[i:i] >> Extracts Rows as df - - - - - - - - - - - - - - - - - - - -
np.mean(mtx, axis = 1) >> Rows mean df[df.c1 > n] >> Extracts Row by cond. I df.pivot(columns = c2, index = c1, values = v)
df[df.c1.condition] >> Extracts Row by cond. II MERGE METHODS
- - - - - - - - - - - - - - - - - - - -
df.reset_index() >> Reset the index pd.merge(df1, df2*) >> Merge method I
drop = True >> Without inserting it df1.merge(df2) >> Merge method II
inplace = True >> Modify overwriting df1.merge(df2).merge(df3)
* > how = ‘outer’ \ ‘inner’ \ ‘right’ \ ‘left’
ADD AND RENAME COLUMNS - - - - - - - - - - - - - - - - - - - -
df[columns] = list >> Adding a column pd.merge(df1, df2, left_on = c1, right_on = c3)*
- - - - - - - - - - - - - - - - - - - - >> To merge 2 data frame with same column
RENAMING COLUMNS: * > suffixes = [name1, name2]
df.columns = list >> Modifying names - - - - - - - - - - - - - - - - - - - -
df.rename(columns = {old:new}, inplace=True) pd.concat([df1, df2])

APPLY MODIFICATIONS & LAMBDA SORTING METHODS

df[col] = df.c1.apply() >> Modify column df.sort_values(by = [‘c1‘, ‘c2‘], ascending = False)
df[col] = df.c1-apply(lb) >> lb = lambda
- - - - - - - - - - - - - - - - - - - -
lb = lambda row: row.c1 >> Lambda in rows
df[col] = df.apply(lb, axis = 1)

You might also like