Docsity

Python cheat sheet for beginners, Cheat Sheet of Computer science

Toggle sidebar
bg1
>How to use this cheat sheet
Python is the most popular programming language in data science. It is easy to learn and comes with a wide array of
powerful libraries for data analysis. This cheat sheet provides beginners and intermediate users a guide to starting
using python. Use it to jump-start your journey with python. If you want more detailed Python cheat sheets, check out
the following cheat sheets below๎˜•
Importing data in python Data wrangling in pandas
Python Basics
Learn Python online at www.DataCamp.com
Python Cheat Sheet for Beginners
>Accessing help and getting object types
1 1
'a'
+ # Everything after the hash symbol is ignored by Pytho๎šจ
# Display the documentation for the max functio๎šจ
# Get the type of an object โ€” this returns str
help(max)
type( )
>Importing packages
Python packages are a collection of useful tools developed by the open-source community. They extend the
capabilities of the python language. To install a new package (for example, pandas), you can go to your command
prompt and type in pip install pandas. Once a package is installed, you can import it as follows๎›—
pandas
pandas pd
pandas DataFrame
import
import as
from import
#
I
mport a pac
k
age
w
ithout an alia
๎˜‰
#
I
mport a pac
k
age
w
ith an alia
๎˜‰
#
I
mport an object from a pac
k
ag
๎˜Ž
>
T
he working directory
The working directory is the default file path that python reads or saves files into.
A
n example of the working directory
is
โ€
C
://
file
/
path
"
. The os library is needed to set and get the working directory๎›—
os
os
.
getc
w
d()
os
.
setc
w
d( )
import #
I
mport the operating system pac
k
ag
๎˜Ž
# Get the current director
๎™ฆ
#
S
et the
w
or
k
ing directory to a ne
w
file path
"
ne
w/w
or
k
ing
/
directory
"
>
O
perators
A
rithmetic operators
1
02
37
1
02
37
4
6
22
7
+
-
*
/
#
A
dd t
w
o numbers
w
ith
๎šฆ
#
S
ubtract a number
w
ith
๎šญ
#
M
ultiply t
w
o numbers
w
ith
๎šก
# Divide a number by another
w
ith
๎šž
22
7
3
4
22
7
//
^
%
#
I
nteger divide a number
w
ith
/๎šž
#
R
aise to the po
w
er
w
ith
๎›„
#
R
eturns 1 # Get the remainder after
division
w
ith
๎›ƒ
A
ssignment operators
a
=
x
[ ]
=
5
0
1
#
A
ssign a value to
๎˜ƒ
#
C
hange the value of an item in a list
N
umeric comparison operators
3
3
3 3
3
1
==
!
=
>
#
T
est for e
q
uality
w
ith
=
๎˜ฌ
#
T
est for ine
q
uality
w
ith
!๎˜ฌ
#
T
est greater than
w
ith
๎˜จ
3 3
3 4
3 4
>
=
<
<
=
#
T
est greater than or e
q
ual to
w
ith
>๎˜ฌ
#
T
est less than
w
ith
๎™„
#
T
est less than or e
q
ual to
w
ith
<
=
L
ogical operators
~
(
==
)
(
!
=
)
&
(
<
)
2 2
1 1 1 1
#
L
ogical
NOT
w
ith
๎™ต
#
L
ogical
A
N
D
w
ith
&
(
>
=
)
|
(
<
)
(
!
=
)
^
(
<
)
1 1 1 1
1 1 1 1
#
L
ogical
O
R
w
ith
๎šŒ
#
L
ogical
XO
R
w
ith
^
>
G
etting started with lists
A
list is an ordered and changeable se
q
uence of elements. It can hold integers, characters, floats, strings, and even objects.
Creating lists
#
C
reate lists
w
ith
[]
,
elements separated by comma
๎˜‰
x
=
[
,
,
๎›œ
1
3 2
L
ist functions and methods
x
.
(x)
x
.
sort()
(x)
x
.
()
x
.
count( )
sorted
reversed
reversed
#
R
eturn a sorted copy of the list e
.
g
.
,
[
1
,
2
,
3
๎›œ
#
S
orts the list in
-
place (replaces x
๎˜‚
#
R
everse the order of elements in x e
.
g
.
,
[2
,
3
,
1
๎›œ
#
R
everse the list in
-
place
๎˜Ÿ
#
C
ount the number of element
2
in the lis
๎˜š
2
Python lists are
z
ero-indexed (the first element has index
0
).
F
or ranges, the first element is included but the last is not
๎˜ฑ
x
=
[
,
,
,
,
]
x
[ ]
x
[ ]
# Define the lis
๎˜š
๎˜Ÿ
#
S
elect the
0
th element in the lis
๎˜š
#
S
elect the last element in the lis
๎˜š
'a' 'b' 'c' 'd' 'e'
0
-
1
x
[
:
]
x
[
:
]
x
[
:
]
1
3
2
3
#
S
elect 1st (inclusive) to
3
rd (exclusive
๎˜‚
#
S
elect the
2
nd to the en
๎™ฎ
#
S
elect
0
th to
3
rd (exclusive
๎˜‚
# Define the x and y list
๎˜‰
x
=
[
,
,
]
๎˜Ÿ
y
=
[
,
,
๎›œ
1
3 6
1
0
1
5 2
1
x + y
*
x
#
R
eturns
[
1
,
3
,
6
,
1
0
,
1
5
,
2
1
]
๎˜Ÿ
#
R
eturns
[
1
,
3
,
6
,
1
,
3
,
6
,
1
,
3
,
6]
3
>
G
etting started with dictionaries
A
dictionary stores data values in key-value pairs. That is, unlike lists which are indexed by position, dictionaries are indexed
by their keys, the names of which must be uni
q
ue.
Creating dictionaries
#
C
reate a dictionary
w
ith
{๎›ต
{ :
,
:
,
:
๎›ต
'a' 1 'b'
4
'c'
9
D
ictionary functions and methods
Selecting dictionary elements
x
=
{ :
,
:
,
:
}
x
.k
eys()
x
.
values()
'a' 1 'b'
2
'c'
3
# Define the x ditionar
๎™„
# Get the
k
eys of a dictionary
,
returns dict
_
k
eys(
[
'a'
,
'b'
,
'c'
]
๎˜‚
# Get the values of a dictionary
,
returns dict
_
values(
[
1
,
2
,
3]
)
๎˜Ÿ
x
[ ]
'a' # 1 # Get a value from a dictionary by specifying the
k
e
๎™„
>
N
um
P
y arrays
N
umPy is a python package for scientific computing. It provides multidimensional array objects and efficient operations
on them. To import
N
umPy, you can run this Python code
๎š›
import numpy as n
๎šƒ
Creating arrays
#
C
onvert a python list to a
N
umPy arra
๎™ฆ
1
2 3
#
R
eturns array(
[
1
,
2
,
3]
๎˜‚
#
R
eturn a se
q
uence from start (inclusive) to end (exclusive
๎šฎ
#
R
eturns array(
[
1
,
2
,
3
,
4]
๎˜‚
#
R
eturn a stepped se
q
uence from start (inclusive) to end (exclusive
๎šฎ
#
R
eturns array(
[
1
,
3]
๎˜‚
#
R
epeat values n time
๎šผ
#
R
eturns array(
[
1
,
1
,
1
,
3
,
3
,
3
,
6
,
6
,
6]
๎˜‚
#
R
epeat values n time
๎˜‰
#
R
eturns array(
[
1
,
3
,
6
,
1
,
3
,
6
,
1
,
3
,
6]
๎˜‚
np
.
array(
[
,
,
]
)
np
.
arange(
,
)
np
.
arange(
, ,
)
np
.
repeat(
[
, ,
]
,
)
np
.
tile(
[
,
,
]
,
)
1
5
1
5 2
1
3 6 3
1
3 6 3
>
M
ath
f
unctions and methods
np
.
q
uantile(x
,
q
)
np
.
(x
,
n)
np
.
var(x)
np
.
std(x)
#
C
alculate
q
-
th
q
uantile
๎˜Ÿ
#
R
ound to n decimal places
๎˜Ÿ
#
C
alculate varianc
๎˜Ž
#
C
alculate standard deviatio๎šจ
round
A
ll functions take an array as the input.
np
.
log(x)
np
.
exp(x)
np
.
(x)
np
.
(x)
np
.
(x)
np
.
mean(x)
#
C
alculate logarith
๎™“
#
C
alculate exponentia
๎™›
# Get maximum valu
๎˜Ž
# Get minimum valu
๎˜Ž
#
C
alculate su
๎™“
#
C
alculate mean
max
min
sum
>
G
etting started with characters and strings
#
C
reate a string
w
ith double or single
q
uote
๎šผ
# Embed a
q
uote in string
w
ith the escape character
๎™ท
#
C
reate multi
-
line strings
w
ith triple
q
uote
๎˜‰
str # Get the character at a specific positio๎šจ
str # Get a substring from starting to ending index (exclusive
๎˜‚
"
Data
C
amp
๎šท
"
H
e said
,
\
"
Data
C
amp
\
"
๎šท
""
๎šธ
A
Frame of Dat
๎˜ƒ
T
idy
,
M
ine
,
A
naly
z
e
I
๎˜š
N
o
w
Y
ou
H
ave
M
eanin
๎šš
C
itation
:
https
:
//
mdsr
-
boo
k.
github
.
io
/
hai
k
us
.
htm
๎™›
""
๎šน
0
0 2
[ ]
[
:
]
Combining and splitting strings
"
Data
"
"
Framed
"
3
"
data
"
"
bee
k
eepers
" "
e
"
+
๎˜Ÿ
*
๎˜Ÿ
.
split( )
#
C
oncatenate strings
w
ith +
,
this returns 'DataFramed'
#
R
epeat strings
w
ith
*
,
this returns 'data data data '
#
S
plit a string on a delimiter
,
returns
[
'b'
,
''
,
'
k
'
,
''
,
'p'
,
'rs'
]
๎˜Ÿ
#
C
oncatenate DataFrames verticall
๎™„
#
C
oncatenate DataFrames hori
z
ontall
๎™„
# Get ro
w
s matching a conditio๎šจ
# Drop columns by nam
๎˜Ž
#
R
ename column
๎˜‰
#
A
dd a ne
w
colum๎šจ
pd
.
concat(
[
df
,
df
]
๎˜‚
pd
.
concat(
[
df
,
df
]
,
axis
=
๎˜‚
df
.
q
uery(
๎˜‚
df
.
drop(columns
=[ ]
๎˜‚
df
.
rename(columns
=
{ :
}
๎˜‚
df
.
assign(temp
_
f
=
/
*
df
[ ]
+ )
"
columns
"
'logical
_
condition'
'col
_
name'
"
oldname
" "
ne
w
name
"
9
5
'temp
_
c'
32
#
C
alculate the mean of each colum๎šจ
# Get summary statistics by colum๎šจ
# Get uni
q
ue ro
w๎˜‰
#
S
ort by values in a colum๎šจ
# Get ro
w
s
w
ith largest values in a colum๎šจ
df
.
mean(
๎˜‚
df
.
agg(aggregation
_
function
๎˜‚
df
.
drop
_
duplicates(
๎˜‚
df
.
sort
_
values(by
=
๎˜‚
df
.
nlargest(n
,
๎˜‚
'col
_
name'
'col
_
name'
>
G
etting started with
D
ata
F
rames
Pandas is a fast and powerful package for data analysis and manipulation in python. To import the package, you can
use import pandas as pd.
A
pandas
D
ata
F
rame is a structure that contains two-dimensional data stored as rows and
columns.
A
pandas series is a structure that contains one-dimensional data
๎˜ฑ
Creating
D
ata
F
rames
#
C
reate a dataframe from a dictionar
๎™„
pd
.
DataFrame(
๎˜˜
:
[
,
,
]
๎˜“
:
np
.
array(
[
,
,
]
)
๎˜“
:
[
,
,
๎›œ
}
)
'a' 1
2 3
'b'
446
'c' 'x' 'x' 'y'
#
C
reate a dataframe from a list of dictionarie
๎˜‰
pd
.
DataFrame(
๎™“
{ :
,
:
,
:
}
,
๎˜Ÿ
{ :
,
:
,
:
}
,
๎˜Ÿ
{ :
,
:
,
: ๎›ต
]
๎˜‚
'a' 1 'b'
4
'c' 'x'
'a' 1 'b'
4
'c' 'x'
'a'
3
'b'
6
'c' 'y'
Selecting
D
ata
F
rame
E
lements
Select a row, column or element from a dataframe.
R
emember
:
all positions are counted from
z
ero, not one๎›—
df
.
iloc
[
๎›œ
df
[
๎›œ
df
[[
,
]]
๎˜Ÿ
df
.
iloc
[
:
,
๎›œ
df
.
iloc
[
, ๎›œ
#
S
elect the
3
rd ro
๎šฉ
#
S
elect one column by nam
๎˜Ž
#
S
elect multiple columns by name
๎˜‰
#
S
elect
2
nd colum๎šจ
#
S
elect the element in the
3
rd ro
w
,
2
nd colum๎šจ
3
'col'
'col1' 'col
2
'
2
3
2
M
anipulating
D
ata
F
rames
Selecting list elements
Concatenating lists
M
utate strings
str
str
str
str
str
=
.
upper()
.
lo
w
er()
.
title()
.
replace(
,
)
"
J
ac
k
and
J
ill
"
"
J
"
"
P
"
# Define st
๎˜›
#
C
onvert a string to uppercase
,
returns '
J
A
C
K
A
N
D
J
I
LL
๎˜‹
#
C
onvert a string to lo
w
ercase
,
returns 'jac
k
and jill'
๎˜Ÿ
#
C
onvert a string to title case
,
returns '
J
ac
k
A
nd
J
ill
๎˜‹
#
R
eplaces matches of a substring
w
ith another
,
returns 'Pac
k
and Pill
๎˜‹

Partial preview of the text

Download Python cheat sheet for beginners and more Cheat Sheet Computer science in PDF only on Docsity!

> How to use this cheat sheet

Python is the most popular programming language in data science. It is easy to learn and comes with a wide array of powerful libraries for data analysis. This cheat sheet provides beginners and intermediate users a guide to starting using python. Use it to jump-start your journey with python. If you want more detailed Python cheat sheets, check out the following cheat sheets below:

Importing data in python Data wrangling in pandas

Python Basics

Learn Python online at www.DataCamp.com

Python Cheat Sheet for Beginners

> Accessing help and getting object types

'a'

  • Everything after the hash symbol is ignored by Python

Display the documentation for the max function

Get the type of an object โ€” this returns str

help(max) type( )

> Importing packages

Python packages are a collection of useful tools developed by the open-source community. They extend the capabilities of the python language. To install a new package (for example, pandas), you can go to your command prompt and type in pip install pandas. Once a package is installed, you can import it as follows.

pandas pandas pd pandas DataFrame

import import as from import

Import a package without an alias

Import a package with an alias

Import an object from a package

> The working directory

The working directory is the default file path that python reads or saves files into. An example of the working directory is โ€C://file/path". The os library is needed to set and get the working directory.

os os.getcwd() os.setcwd( )

import # Import the operating system package

Get the current directory

"new/working/directory" # Set the working directory to a new file path

> Operators

Arithmetic operators

Add two numbers with +

Subtract a number with -

Multiply two numbers with *

Divide a number by another with /

^

Integer divide a number with //

Raise to the power with ^

Returns 1 # Get the remainder after

division with %

Assignment operators

a = x[ ] =

Assign a value to a

Change the value of an item in a list

Numeric comparison operators

Test for equality with ==

Test for inequality with !=

Test greater than with >

Test greater than or equal to with >=

Test less than with <

Test less than or equal to with <=

Logical operators

Logical NOT with ~

Logical AND with &

( != ) ^ ( < )

Logical OR with |

Logical XOR with ^

> Getting started with lists

A list is an ordered and changeable sequence of elements. It can hold integers, characters, floats, strings, and even objects.

Creating lists

Create lists with [], elements separated by commas

x = [ 1 , 3 , 2 ]

List functions and methods

x. (x) x.sort() (x) x. () x.count( )

sorted

reversed reversed

Return a sorted copy of the list e.g., [ 1 , 2 , 3 ]

Sorts the list in-place (replaces x)

Reverse the order of elements in x e.g., [2, 3 , 1 ]

Reverse the list in-place

2 # Count the number of element 2 in the list

Python lists are zero-indexed (the first element has index 0 ). For ranges, the first element is included but the last is not.

x = [ , , , , ] x[ ] x[ ]

Define the list

Select the 0 th element in the list

Select the last element in the list

'a' 'b' 'c' 'd' 'e' 0

  • 1

x[ : ] x[ :] x[: ]

Select 1st (inclusive) to 3 rd (exclusive)

Select the 2 nd to the end

Select 0 th to 3 rd (exclusive)

Define the x and y lists

x = [ , , ] y = [ , , ]

x + y

  • x

Returns [ 1 , 3 , 6 , 10 , 15 , 21 ]

3 # Returns [ 1 , 3 , 6 , 1 , 3 , 6 , 1 , 3 , 6]

> Getting started with dictionaries

A dictionary stores data values in key-value pairs. That is, unlike lists which are indexed by position, dictionaries are indexed by their keys, the names of which must be unique.

Creating dictionaries

Create a dictionary with {}

{ 'a': 1 , 'b': 4 , 'c': 9 }

Dictionary functions and methods

Selecting dictionary elements

x = { : , : , : } x.keys() x.values()

'a' 1 'b' 2 'c' 3 # Define the x ditionary

Get the keys of a dictionary, returns dict_keys(['a', 'b', 'c'])

Get the values of a dictionary, returns dict_values([ 1 , 2 , 3])

x[ 'a'] # 1 # Get a value from a dictionary by specifying the key

> NumPy arrays

NumPy is a python package for scientific computing. It provides multidimensional array objects and efficient operations on them. To import NumPy, you can run this Python code import numpy as np

Creating arrays

Convert a python list to a NumPy array

1 2 3 # Returns array([ 1 , 2 , 3])

Return a sequence from start (inclusive) to end (exclusive)

Returns array([ 1 , 2 , 3 , 4])

Return a stepped sequence from start (inclusive) to end (exclusive)

Returns array([ 1 , 3])

Repeat values n times

Returns array([ 1 , 1 , 1 , 3 , 3 , 3 , 6 , 6 , 6])

Repeat values n times

Returns array([ 1 , 3 , 6 , 1 , 3 , 6 , 1 , 3 , 6])

np.array([ , , ])

np.arange( , )

np.arange( , , )

np.repeat([ , , ], )

np.tile([ , , ], )

> Math^ functions and methods

np.quantile(x, q) np. (x, n) np.var(x) np.std(x)

Calculate q-th quantile

Round to n decimal places

Calculate variance

Calculate standard deviation

round

All functions take an array as the input. np.log(x) np.exp(x) np. (x) np. (x) np. (x) np.mean(x)

Calculate logarithm

Calculate exponential

Get maximum value

Get minimum value

Calculate sum

Calculate mean

max min sum

> Getting started with characters and strings

Create a string with double or single quotes

Embed a quote in string with the escape character \

Create multi-line strings with triple quotes

str # Get the character at a specific position

str # Get a substring from starting to ending index (exclusive)

"DataCamp"

"He said, "DataCamp""

A Frame of Data

Tidy, Mine, Analyze It

Now You Have Meaning

Citation: https://mdsr-book.github.io/haikus.html

"""

0 0 2

[ ]

[ : ]

Combining and splitting strings

"Data" "Framed" 3 "data " "beekeepers" "e"

.split( )

Concatenate strings with +, this returns 'DataFramed'

Repeat strings with *, this returns 'data data data '

Split a string on a delimiter, returns ['b', '', 'k', '', 'p', 'rs']

Concatenate DataFrames vertically

Concatenate DataFrames horizontally

Get rows matching a condition

Drop columns by name

Rename columns

Add a new column

pd.concat([df, df])

pd.concat([df,df],axis= )

df.query( )

df.drop(columns=[ ])

df.rename(columns={ : })

df.assign(temp_f= / * df[ ] + )

"columns"

'logical_condition'

'col_name'

"oldname" "newname"

9 5 'temp_c' 32

Calculate the mean of each column

Get summary statistics by column

Get unique rows

Sort by values in a column

Get rows with largest values in a column

df.mean()

df.agg(aggregation_function)

df.drop_duplicates()

df.sort_values(by= )

df.nlargest(n, )

'col_name'

'col_name'

> Getting started with^ DataFrames

Pandas is a fast and powerful package for data analysis and manipulation in python. To import the package, you can use import pandas as pd. A pandas DataFrame is a structure that contains two-dimensional data stored as rows and columns. A pandas series is a structure that contains one-dimensional data.

Creating DataFrames

Create a dataframe from a dictionary

pd.DataFrame({

: [ , , ],

: np.array([ , , ]),

: [ , , ]

})

'a' 1 2 3 'b' 4 4 6 'c' 'x' 'x' 'y'

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'

Selecting DataFrame Elements

Select a row, column or element from a dataframe. Remember: all positions are counted from zero, not one.

df.iloc[ ]

df[ ]

df[[ , ]]

df.iloc[:, ]

df.iloc[ , ]

Select the 3 rd row

Select one column by name

Select multiple columns by names

Select 2 nd column

Select the element in the 3 rd row, 2 nd column

'col'

'col1' 'col 2 '

2

3 2

Manipulating DataFrames

Selecting list elements

Concatenating lists

Mutate strings

str str str str str

.upper() .lower() .title() .replace( , )

"Jack and Jill"

"J" "P"

Define str

Convert a string to uppercase, returns 'JACK AND JILL'

Convert a string to lowercase, returns 'jack and jill'

Convert a string to title case, returns 'Jack And Jill'

Replaces matches of a substring with another, returns 'Pack and Pill'