row = 'sofa|2000|buy|Uppsala'
fields = row.split('|')
price = fields[1]
if price == 2000:
print('The price is a number!')
if price == '2000':
print('The price is a string!')
The price is a string!
print(sorted([ 2000, 30, 100 ]))
print(sorted(['2000', '30', '100']))
# Hint: is `'30' > '2000'`?
[30, 100, 2000] ['100', '2000', '30']
'2000'
and '0.5'
and '1e9'
1
, 0
, '1'
, '0'
, ''
, {}
'C'
in the argument string.row = 'sofa|2000|buy|Uppsala'
fields = row.split('|')
price = int(fields[1])
if price == 2000:
print('The price is a number!')
if price == '2000':
print('The price is a string!')
The price is a number!
print(sorted([ 2000, 30, 100 ]))
print(sorted(['2000', '30', '100']))
# Hint: is `'30' > '2000'`?
[30, 100, 2000] ['100', '2000', '30']
Each type store a specific type of information
int
for integers,float
for floating point values (decimals),str
for strings,list
for lists,dict
for dictionaries.Each type supports different operations, functions and methods.
30 > 2000
False
'30' > '2000'
True
30 > int('2000')
False
'ACTG'.lower()
'actg'
[1, 2, 3].lower()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-4e1a84c0439c> in <module> ----> 1 [1, 2, 3].lower() AttributeError: 'list' object has no attribute 'lower'
'2000'
and '0.5'
and '1e9'
int('2000')
2000
int('0.5')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-12-6d0b04c882d1> in <module> ----> 1 int('0.5') ValueError: invalid literal for int() with base 10: '0.5'
int('1e9')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-13-cb568d180cc9> in <module> ----> 1 int('1e9') ValueError: invalid literal for int() with base 10: '1e9'
float('2000')
2000.0
int(float('1.5'))
1
int(float('1e9'))
1000000000
1
, 0
, '1'
, '0'
, ''
, {}
bool(1)
True
bool(0)
False
bool('1')
True
bool('0')
True
bool('')
False
bool({})
False
values = [1, 0, '', '0', '1', [], [0]]
for x in values:
if x:
print(repr(x), 'is true!')
else:
print(repr(x), 'is false!')
1 is true! 0 is false! '' is false! '0' is true! '1' is true! [] is false! [0] is true!
list("hello")
['h', 'e', 'l', 'l', 'o']
str(['h', 'e', 'l', 'l', 'o'])
"['h', 'e', 'l', 'l', 'o']"
'_'.join(['h', 'e', 'l', 'l', 'o'])
'h_e_l_l_o'
genre_list = ["comedy", "drama", "drama", "sci-fi"]
genre_list
['comedy', 'drama', 'drama', 'sci-fi']
genres = set(genre_list)
'drama' in genres
True
genre_counts = {"comedy": 1, "drama": 2, "sci-fi": 1}
genre_counts
{'comedy': 1, 'drama': 2, 'sci-fi': 1}
movie = {"rating": 10.0, "title": "Toy Story"}
movie
{'rating': 10.0, 'title': 'Toy Story'}
A relation (mapping) between inputs (arguments) and output (return value)
Write a function that counts the number of occurences of 'C'
in the argument string.
'C'
def cytosine_count(nucleotides):
count = 0
for x in nucleotides:
if x == 'c' or x == 'C':
count += 1
return count
count1 = cytosine_count('CATATTAC')
count2 = cytosine_count('tagtag')
print(count1, count2)
2 0
return
are easier to repurpose than those that print
their resultcytosine_count('catattac') + cytosine_count('tactactac')
5
def print_cytosine_count(nucleotides):
count = 0
for x in nucleotides:
if x == 'c' or x == 'C':
count += 1
print(count)
print_cytosine_count('catattac') + print_cytosine_count('tactactac')
2 3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-33-5bbd47c30b94> in <module> 6 print(count) 7 ----> 8 print_cytosine_count('catattac') + print_cytosine_count('tactactac') TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
list_A = ['red', 'green']
list_B = ['red', 'green']
list_B.append('blue')
print(list_A, list_B)
['red', 'green'] ['red', 'green', 'blue']
list_A = ['red', 'green']
list_B = list_A # another name to the SAME list. Aliasing
list_B.append('blue')
print(list_A, list_B)
['red', 'green', 'blue'] ['red', 'green', 'blue']
list_A = ['red', 'green']
list_B = list_A
list_A = []
print(list_A, list_B)
[] ['red', 'green']
list_A = ['red', 'green']
lists = {'A': list_A, 'B': list_A}
print(lists)
lists['B'].append('blue')
print(lists)
{'A': ['red', 'green'], 'B': ['red', 'green']} {'A': ['red', 'green', 'blue'], 'B': ['red', 'green', 'blue']}
list_A = ['red', 'green']
lists = {'A': list_A, 'B': list_A}
print(lists)
lists['B'] = lists['B'] + ['yellow']
print(lists)
{'A': ['red', 'green'], 'B': ['red', 'green']} {'A': ['red', 'green'], 'B': ['red', 'green', 'yellow']}
movies = ['Toy story', 'Home alone']
def some_thriller_movies():
return ['Fargo', 'The Usual Suspects']
movies = some_thriller_movies()
print(movies)
['Fargo', 'The Usual Suspects']
def change_to_drama(movies):
movies = ['Forrest Gump', 'Titanic']
change_to_drama(movies)
print(movies)
['Fargo', 'The Usual Suspects']
def change_to_scifi(movies):
movies.clear()
movies += ['Terminator II', 'The Matrix']
change_to_scifi(movies)
print(movies)
['Terminator II', 'The Matrix']
sorted(list('file'), reverse=True)
['l', 'i', 'f', 'e']
attribute = 'gene_id "unknown gene"'
attribute.split(sep=' ', maxsplit=1)
['gene_id', '"unknown gene"']
# print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
print('x=', end='')
print('1')
x=1
open(file, mode='r', encoding=None) # some arguments omitted
open('files/recipes.txt', 'w', encoding='utf-8')
open('files/recipes.txt', mode='w', encoding='utf-8')
open('files/recipes.txt', encoding='utf-8', mode='w')
def format_sentence(subject, value, end):
return 'The ' + subject + ' is ' + value + end
print(format_sentence('lecture', 'ongoing', '.'))
print(format_sentence('lecture', 'ongoing', end='.'))
print(format_sentence(subject='lecture', value='ongoing', end='...'))
The lecture is ongoing. The lecture is ongoing. The lecture is ongoing...
print(format_sentence(subject='lecture', 'ongoing', '.'))
File "<ipython-input-47-8916632389ec>", line 1 print(format_sentence(subject='lecture', 'ongoing', '.')) ^ SyntaxError: positional argument follows keyword argument
def format_sentence(subject, value, end='.'):
return 'The ' + subject + ' is ' + value + end
print(format_sentence('lecture', 'ongoing'))
print(format_sentence('lecture', 'ongoing', '...'))
The lecture is ongoing. The lecture is ongoing...
None
def format_sentence(subject, value, end='.', second_value=None):
if second_value is None:
return 'The ' + subject + ' is ' + value + end
else:
return 'The ' + subject + ' is ' + value + ' and ' + second_value + end
print(format_sentence('lecture', 'ongoing'))
print(format_sentence('lecture', 'ongoing',
second_value='self-referential', end='!'))
The lecture is ongoing. The lecture is ongoing and self-referential!
None
¶return
bool(None)
False
None == False, None == 0
(False, False)
None
¶None
to the other false values such as 0
, False
and ''
use is None
:counts = {'drama': 2, 'romance': 0}
counts.get('romance'), counts.get('thriller')
(0, None)
counts.get('romance') is None
False
counts.get('thriller') is None
True
values = [None, 1, 0, '', '0', '1', [], [0]]
for x in values:
if x is None:
print(repr(x), 'is None')
if not x:
print(repr(x), 'is false')
if x:
print(repr(x), 'is true')
None is None None is false 1 is true 0 is false '' is false '0' is true '1' is true [] is false [0] is true
Controlling loops - break
for x in lines_in_a_big_file:
if x.startswith('>'): # this is the only line I want!
do_something(x)
...waste of time!
for x in lines_in_a_big_file:
if x.startswith('>'): # this is the only line I want!
do_something(x)
break # break the loop
Controlling loops - continue
for x in lines_in_a_big_file:
if x.startswith('>'): # irrelevant line
# just skip this! don't do anything
do_something(x)
for x in lines_in_a_big_file:
if x.startswith('>'): # irrelevant line
continue # go on to the next iteration
do_something(x)
for x in lines_in_a_big_file:
if not x.startswith('>'): # not irrelevant!
do_something(x)
Another control statement: pass - the placeholder
def a_function():
# I have not implemented this just yet
File "<ipython-input-56-a7f30ec71867>", line 2 # I have not implemented this just yet ^ SyntaxError: unexpected EOF while parsing
def a_function():
# I have not implemented this just yet
pass
a_function()
Check out the module index
How to find the right module?
How to understand it?
How to find the right module?
How to understand it?
import math
help(math.acosh)
Help on built-in function acosh in module math: acosh(x, /) Return the inverse hyperbolic cosine of x.
help(str)
Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __format__(self, format_spec, /) | Return a formatted version of the string as described by format_spec. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(...) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __sizeof__(self, /) | Return the size of the string in memory, in bytes. | | __str__(self, /) | Return str(self). | | capitalize(self, /) | Return a capitalized version of the string. | | More specifically, make the first character have upper case and the rest lower | case. | | casefold(self, /) | Return a version of the string suitable for caseless comparisons. | | center(self, width, fillchar=' ', /) | Return a centered string of length width. | | Padding is done using the specified fill character (default is a space). | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are | interpreted as in slice notation. | | encode(self, /, encoding='utf-8', errors='strict') | Encode the string using the codec registered for encoding. | | encoding | The encoding in which to encode the string. | errors | The error handling scheme to use for encoding errors. | The default is 'strict' meaning that encoding errors raise a | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and | 'xmlcharrefreplace' as well as any other name registered with | codecs.register_error that can handle UnicodeEncodeErrors. | | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. | | expandtabs(self, /, tabsize=8) | Return a copy where all tab characters are expanded using spaces. | | If tabsize is not given, a tab size of 8 characters is assumed. | | find(...) | S.find(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | format(...) | S.format(*args, **kwargs) -> str | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces ('{' and '}'). | | format_map(...) | S.format_map(mapping) -> str | | Return a formatted version of S, using substitutions from mapping. | The substitutions are identified by braces ('{' and '}'). | | index(...) | S.index(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | isalnum(self, /) | Return True if the string is an alpha-numeric string, False otherwise. | | A string is alpha-numeric if all characters in the string are alpha-numeric and | there is at least one character in the string. | | isalpha(self, /) | Return True if the string is an alphabetic string, False otherwise. | | A string is alphabetic if all characters in the string are alphabetic and there | is at least one character in the string. | | isascii(self, /) | Return True if all characters in the string are ASCII, False otherwise. | | ASCII characters have code points in the range U+0000-U+007F. | Empty string is ASCII too. | | isdecimal(self, /) | Return True if the string is a decimal string, False otherwise. | | A string is a decimal string if all characters in the string are decimal and | there is at least one character in the string. | | isdigit(self, /) | Return True if the string is a digit string, False otherwise. | | A string is a digit string if all characters in the string are digits and there | is at least one character in the string. | | isidentifier(self, /) | Return True if the string is a valid Python identifier, False otherwise. | | Call keyword.iskeyword(s) to test whether string s is a reserved identifier, | such as "def" or "class". | | islower(self, /) | Return True if the string is a lowercase string, False otherwise. | | A string is lowercase if all cased characters in the string are lowercase and | there is at least one cased character in the string. | | isnumeric(self, /) | Return True if the string is a numeric string, False otherwise. | | A string is numeric if all characters in the string are numeric and there is at | least one character in the string. | | isprintable(self, /) | Return True if the string is printable, False otherwise. | | A string is printable if all of its characters are considered printable in | repr() or if it is empty. | | isspace(self, /) | Return True if the string is a whitespace string, False otherwise. | | A string is whitespace if all characters in the string are whitespace and there | is at least one character in the string. | | istitle(self, /) | Return True if the string is a title-cased string, False otherwise. | | In a title-cased string, upper- and title-case characters may only | follow uncased characters and lowercase characters only cased ones. | | isupper(self, /) | Return True if the string is an uppercase string, False otherwise. | | A string is uppercase if all cased characters in the string are uppercase and | there is at least one cased character in the string. | | join(self, iterable, /) | Concatenate any number of strings. | | The string whose method is called is inserted in between each given string. | The result is returned as a new string. | | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' | | ljust(self, width, fillchar=' ', /) | Return a left-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | lower(self, /) | Return a copy of the string converted to lowercase. | | lstrip(self, chars=None, /) | Return a copy of the string with leading whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | partition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string. If the separator is found, | returns a 3-tuple containing the part before the separator, the separator | itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing the original string | and two empty strings. | | replace(self, old, new, count=-1, /) | Return a copy with all occurrences of substring old replaced by new. | | count | Maximum number of occurrences to replace. | -1 (the default value) means replace all occurrences. | | If the optional argument count is given, only the first count occurrences are | replaced. | | rfind(...) | S.rfind(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | rindex(...) | S.rindex(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | rjust(self, width, fillchar=' ', /) | Return a right-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | rpartition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string, starting at the end. If | the separator is found, returns a 3-tuple containing the part before the | separator, the separator itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing two empty strings | and the original string. | | rsplit(self, /, sep=None, maxsplit=-1) | Return a list of the words in the string, using sep as the delimiter string. | | sep | The delimiter according which to split the string. | None (the default value) means split according to any whitespace, | and discard empty strings from the result. | maxsplit | Maximum number of splits to do. | -1 (the default value) means no limit. | | Splits are done starting at the end of the string and working to the front. | | rstrip(self, chars=None, /) | Return a copy of the string with trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | split(self, /, sep=None, maxsplit=-1) | Return a list of the words in the string, using sep as the delimiter string. | | sep | The delimiter according which to split the string. | None (the default value) means split according to any whitespace, | and discard empty strings from the result. | maxsplit | Maximum number of splits to do. | -1 (the default value) means no limit. | | splitlines(self, /, keepends=False) | Return a list of the lines in the string, breaking at line boundaries. | | Line breaks are not included in the resulting list unless keepends is given and | true. | | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. | | strip(self, chars=None, /) | Return a copy of the string with leading and trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | swapcase(self, /) | Convert uppercase characters to lowercase and lowercase characters to uppercase. | | title(self, /) | Return a version of the string where each word is titlecased. | | More specifically, words start with uppercased characters and all remaining | cased characters have lower case. | | translate(self, table, /) | Replace each character in the string using the given translation table. | | table | Translation table, which must be a mapping of Unicode ordinals to | Unicode ordinals, strings, or None. | | The table must implement lookup/indexing via __getitem__, for instance a | dictionary or list. If this operation raises LookupError, the character is | left untouched. Characters mapped to None are deleted. | | upper(self, /) | Return a copy of the string converted to uppercase. | | zfill(self, width, /) | Pad a numeric string with zeros on the left, to fill a field of the given width. | | The string is never truncated. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | maketrans(...) | Return a translation table usable for str.translate(). | | If there is only one argument, it must be a dictionary mapping Unicode | ordinals (integers) or characters to Unicode ordinals, strings or None. | Character keys will be then converted to ordinals. | If there are two arguments, they must be strings of equal length, and | in the resulting dictionary, each character in x will be mapped to the | character at the same position in y. If there is a third argument, it | must be a string, whose characters will be mapped to None in the result.
help(math.sqrt)
# install packages using: pip
# Dimitris' protip: install packages using conda
Help on built-in function sqrt in module math: sqrt(x, /) Return the square root of x.
math.sqrt(3)
1.7320508075688772
import math
math.sqrt(3)
1.7320508075688772
import math as m
m.sqrt(3)
1.7320508075688772
from pprint import pprint
Remember help()
?
Works because somebody else has documented their code!
def process_file(filename, chrom, pos):
"""
Read a vcf file, search for lines matching
chromosome chrom and position pos.
Print the genotypes of the matching lines.
"""
for line in open(filename):
if not line.startswith('#'):
col = line.split('\t')
if col[0] == chrom and col[1] == pos:
print(col[9:])
help(process_file)
Help on function process_file in module __main__: process_file(filename, chrom, pos) Read a vcf file, search for lines matching chromosome chrom and position pos. Print the genotypes of the matching lines.
help(process_file)
Help on function process_file in module __main__: process_file(filename, chrom, pos) Read a vcf file, search for lines matching chromosome chrom and position pos. Print the genotypes of the matching lines.
Your code may have two types of users:
Write documentation for both of them!
"""
What does this function do?
"""
# implementation details
At the beginning of the file
"""
This module provides functions for...
"""
`
For every function
def make_list(x):
"""Returns a random list of length x."""
pass
my_list[5] += other_list[3] # explain why you do this!
title = 'Toy Story'
rating = 10
print('The result is: ' + title + ' with rating: ' + str(rating))
The result is: Toy Story with rating: 10
# f-strings (since python 3.6)
print(f'The result is: {title} with rating: {rating}')
The result is: Toy Story with rating: 10
# format method
print('The result is: {} with rating: {}'.format(title, rating))
The result is: Toy Story with rating: 10
# the ancient way (python 2)
print('The result is: %s with rating: %s' % (title, rating))
The result is: Toy Story with rating: 10
Learn more from the Python docs: https://docs.python.org/3.4/library/string.html#format-string-syntax
pick_movie(year=1996, rating_min=8.5)
The Bandit
pick_movie(rating_max=8.0, genre="Mystery")
Twelve Monkeys
DataFrame
type:import pandas as pd
df = pd.DataFrame({
'age': [1,2,3,4],
'circumference': [2,3,5,10],
'height': [30, 35, 40, 50]
})
df
age | circumference | height | |
---|---|---|---|
0 | 1 | 2 | 30 |
1 | 2 | 3 | 35 |
2 | 3 | 5 | 40 |
3 | 4 | 10 | 50 |
pd.read_table
: tab separated values .tsv
pd.read_csv
: comma separated values .csv
pd.read_excel
: Excel spreadsheets .xlsx
For a data frame df
: df.write_table()
, df.write_csv()
, df.write_excel()
!cat ../downloads/Orange_1.tsv
age circumference height 1 2 30 2 3 35 3 5 40 4 10 50
df = pd.read_table('../downloads/Orange_1.tsv')
df
age | circumference | height | |
---|---|---|---|
0 | 1 | 2 | 30 |
1 | 2 | 3 | 35 |
2 | 3 | 5 | 40 |
3 | 4 | 10 | 50 |
age
, circumference
, height
dataframe.columnname
dataframe['columnname']
df.columns
Index(['age', 'circumference', 'height'], dtype='object')
df[['height', 'age']]
height | age | |
---|---|---|
0 | 30 | 1 |
1 | 35 | 2 |
2 | 40 | 3 |
3 | 50 | 4 |
df.height
0 30 1 35 2 40 3 50 Name: height, dtype: int64
df[['age', 'circumference']].describe()
age | circumference | |
---|---|---|
count | 4.000000 | 4.000000 |
mean | 2.500000 | 5.000000 |
std | 1.290994 | 3.559026 |
min | 1.000000 | 2.000000 |
25% | 1.750000 | 2.750000 |
50% | 2.500000 | 4.000000 |
75% | 3.250000 | 6.250000 |
max | 4.000000 | 10.000000 |
df['age'].std()
1.2909944487358056
import math
df['radius'] = df['circumference'] / 2.0 / math.pi
df
age | circumference | height | radius | |
---|---|---|---|---|
0 | 1 | 2 | 30 | 0.318310 |
1 | 2 | 3 | 35 | 0.477465 |
2 | 3 | 5 | 40 | 0.795775 |
3 | 4 | 10 | 50 | 1.591549 |
dataframe.iloc[index]
dataframe.iloc[start:stop]
df.iloc[1:3]
age | circumference | height | radius | |
---|---|---|---|---|
1 | 2 | 3 | 35 | 0.477465 |
2 | 3 | 5 | 40 | 0.795775 |
!head -n 6 ../downloads/Orange.tsv
Tree age circumference 1 118 30 1 484 58 1 664 87 1 1004 115 1 1231 120
df = pd.read_table('../downloads/Orange.tsv') # , index_col=0)
df.iloc[0:5] # can also use .head()
Tree | age | circumference | |
---|---|---|---|
0 | 1 | 118 | 30 |
1 | 1 | 484 | 58 |
2 | 1 | 664 | 87 |
3 | 1 | 1004 | 115 |
4 | 1 | 1231 | 120 |
df.Tree.unique()
array([1, 2, 3])
type(pd.DataFrame({"genre": ['Thriller', 'Drama'], "rating": [10, 9]}).rating.iloc[0])
numpy.int64
#young = df[df.age < 200]
#young
df[df.age < 1000]
Tree | age | circumference | |
---|---|---|---|
0 | 1 | 118 | 30 |
1 | 1 | 484 | 58 |
2 | 1 | 664 | 87 |
7 | 2 | 118 | 33 |
8 | 2 | 484 | 69 |
9 | 2 | 664 | 111 |
14 | 3 | 118 | 30 |
15 | 3 | 484 | 51 |
16 | 3 | 664 | 75 |
df.loc[ df.age < 200 ]
df.head()
Tree | age | circumference | |
---|---|---|---|
0 | 1 | 118 | 30 |
1 | 1 | 484 | 58 |
2 | 1 | 664 | 87 |
3 | 1 | 1004 | 115 |
4 | 1 | 1231 | 120 |
max_c = df.circumference.max()
print(max_c)
203
df[df.circumference == max_c]
Tree | age | circumference | |
---|---|---|---|
12 | 2 | 1372 | 203 |
13 | 2 | 1582 | 203 |
df.columnname.plot()
small_df = pd.read_table('../downloads/Orange_1.tsv')
small_df.plot(x='age', y='height')
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f43b912e0>
What if no plot shows up?
%pylab inline # jupyter notebooks
or
import matplotlib.plot as plt
plt.show()
df[['circumference', 'age']].plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f4348c820>
df[['circumference', 'age']].plot(kind='bar', figsize=(12, 8), fontsize=16)
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f433e1ee0>
df.plot(kind="scatter", x="column_name", y="other_column_name")
df.plot(kind='scatter', x='age', y='circumference',
figsize=(12, 8), fontsize=14)
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f43419a90>
dataframe.plot(kind="line", x=..., y=...)
tree1 = df[df['Tree'] == 1]
tree1.plot(x='age', y='circumference',
fontsize=14, figsize=(12,8))
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f43295a00>
dataframe.plot(kind="line", x="..", y="...")
df.plot(kind='line', x='age', y='circumference',
figsize=(12, 8), fontsize=14)
<matplotlib.axes._subplots.AxesSubplot at 0x7f3f431f2c40>
:(
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
tree_names = df['Tree'].unique()
print('tree_names:', tree_names)
for tree_name in tree_names:
sub_df = df[df['Tree'] == tree_name]
sub_df.plot(x='age', y='circumference', kind='line',
ax=ax, fontsize=14, figsize=(8,6))
tree_names: [1 2 3]
Read the Orange_1.tsv
Use Pandas to read IMDB
Extra exercises: