Python For Data Science
Python Basics
Variables and data types
Variable Assignment
>>> x=5
>>> x
5
Calculate with variables
>>> x+2 Sum of two variables
7
>>> x-2 Subtraction of two variables
3
>>> x*2 Multiplication of two variables
10
>>> x**2 Exponentiation of a variable
25
>>> x%2 Remainder of a variable
1
>>> x/float(2) Division of a variable
2.5
Types and Type Conversion
str() '5', '3.45', 'True' Variables to strings
int() 5, 3, 1 Variables to integers
float() 5.0, 1.0 Variables to floats
bool() True, True, True Variables to booleans
Strings
>>> my_string = 'thisStringIsAwesome'
>>> my_string
'thisStringIsAwesome'
String Operations
>>> my_string * 2
'thisStringIsAwesomethisStringIsAwesome'
>>> my_string + 'Innit'
'thisStringIsAwesomeInnit'
>>> 'm' in my_string
True
>>> my_string[3]
>>> my_string[4:9]
String Methods
>>> my_string.upper() String to uppercase
>>> my_string.lower() String to lowercase
>>> my_string.count('w') Count String elements
>>> my_string.replace('e', 'i') Replace String elements
>>> my_string.strip() Strip whitespaces
Lists
>>> a = 'is'
>>> b = 'nice'
>>> my_list = ['my', 'list', a, b]
>>> my_list2 = [[4,5,6,7], [3,4,5,6]]
Selecting List Elements
Subset
>>> my_list[1] Select item at index 1
>>> my_list[-3] Select 3rd last item
Slice
>>> my_list[1:3] Select items at index 1 and 2
>>> my_list[1:] Select items after index 0
>>> my_list[:3] Select items before index 3
>>> my_list[:] Copy my_list
Subset Lists of Lists
>>> my_list2[1][0] my_list[list][itemOfList]
>>> my_list2[1][:2]
List Operations
>>> my_list + my_list
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
>>> my_list * 2
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
>>> my_list2 > 4
True
List Methods
>>> my_list.index(a) Get the index of an item
>>> my_list.count(a) Count an item
>>> my_list.append('!') Append an item at a time
>>> my_list.remove('!') Remove an item
>>> del(my_list[0:1]) Remove an item
>>> my_list.reverse() Reverse the list
>>> my_list.extend('!') Append an item
>>> my_list.pop(-1) Remove an item
>>> my_list.insert(0,'!') Insert an item
>>> my_list.sort() Sort the list