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