Functions, methods, and libraries

Python for R Users

Daniel Chen

Instructor

Calling functions

  • R and Python functions work the same
  • Python: Functions and Methods
Python for R Users

Methods vs functions

  • Python is object oriented
    • Attributes
    • Methods
  • Methods are functions that an object can call on itself
  • Functions are called on an object
l = [0, 1, 2, 3, 4]
len(l)   # call a function
l.len()  # not a method
Python for R Users

Periods have a special meaning in Python

Periods have very specific meanings and uses

Python for R Users

Append to list

l = [1, "2", True]

l.append('appended value')

l
[1, '2', True, 'appended value']
Python for R Users

Update a dictionary

d = {'int_value':3, 'bool_value':False, 'str_value':'hello'}

d.update({'str_value':'new_value', 'new_key':'new_value'})

d
{'bool_value': False,
 'int_value': 3,
 'new_key': 'new_value',
 'str_value': 'new_value'}
Python for R Users

Methods are specific to the object

d.append('hello')
 ------------------------------------------------------------------
AttributeError                    Traceback (most recent call last)
<ipython-input-4-42922a99ec56> in <module>()
<hr />-> 1 d.append('hello')

AttributeError: 'dict' object has no attribute 'append'
Python for R Users

Libraries

  • Libraries provide more functionality
  • Arrays and dataframes are not built into Python
  • Arrays and matrices come from numpy
  • Dataframes come from pandas
Python for R Users

Numpy ndarray

R
library(readr)
dat <- read_csv('my_file.csv')
Python
import numpy
arr = numpy.loadtxt('my_file.csv', delimiter=',')

import numpy as np
arr = np.loadtxt('my_file.csv', delimiter=',')
Python for R Users

Pandas DataFrame

import pandas as pd

df = pd.read_csv('my_file.csv')
df.head()
Python for R Users

Let's practice!

Python for R Users

Preparing Video For Download...