Writing Efficient Python Code
  • AI Chat
  • Code
  • Report
  • Beta
    Spinner

    Writing Efficient Python Code

    Run the hidden code cell below to import the data used in this course.

    # Importing pandas
    import pandas as pd
    
    # Reading in the data
    giants_df = pd.read_csv("datasets/baseball.csv")

    Take Notes

    Add notes about the concepts you've learned and code cells with code you want to keep.

    Add your notes here

    # Print the list created using the Non-Pythonic approach
    names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
    i = 0
    new_list= []
    while i < len(names):
        if len(names[i]) >= 6:
            new_list.append(names[i])
        i += 1
    print(names)
    print(new_list)
    # Print the list created by looping over the contents of names
    names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
    better_list = []
    for name in names:
        if len(name) >= 6:
            better_list.append(name)
    print(better_list)
    # Print the list created by using list comprehension
    names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
    best_list = [noname for noname in names if len(noname) >= 6]
    print(best_list)
    import this
    print(type(this))
    # Create a range object that goes from 0 to 5
    nums = range(0, 6)
    print(type(nums))
    
    # Convert nums to a list
    nums_list = list(nums)
    print(nums_list)
    
    # Create a new list of odd numbers from 1 to 11 by unpacking a range object
    nums_list2 = [*range(1,12,2)]
    print(nums_list2)
    """
    enumerate() allows to create an index for each item in the object. Use list comprehension, or even unpack the _enumerate object_ directly into a list, to write a nice simple one-liner.
    """
    
    # Rewrite the for loop to use enumerate
    indexed_names = []
    for i, name in enumerate(names):
        index_name = (i,name)
        indexed_names.append(index_name) 
    print(indexed_names)
    
    # Rewrite the above for loop using list comprehension
    indexed_names_comp = [(i, name) for i,name in enumerate(names)]
    print(indexed_names_comp)
    
    # Unpack an enumerate object with a starting index of one
    indexed_names_unpack = [*enumerate(names, 1)]
    print(indexed_names_unpack)
    # Use map to apply str.upper to each element in names
    names_map  = map(str.upper, names)
    
    # Print the type of the names_map
    print(type(names_map))
    
    # Unpack names_map into a list
    names_uppercase = [list(names_map)]
    
    # Print the list created above
    print(names_uppercase)
    import numpy as np
    
    nni = np.array([1, 2, 3])
    print(nni.dtype)
    nnf = np.array([1, 2.5, 3])
    print(nnf.dtype)
    1) Print the second row of nums.
    2) Print the items of nums that are greater than six.
    3) Create nums_dbl that doubles each number in nums.
    4) Replace the third column in nums with a new column that adds 1 to each item in the original column.
    Hints:

    numpy arrays are zero indexed.

    That means [0,:] will get the first row of a 2D array.

    You can create a boolean index by using an inequality directly on the nums array. For example, nums < 2 will create a boolean index for all items in nums that are less than two.

    Mathematical operations are broadcasted to each element of a numpy array by default. (i.e., the command nums + 1 will add one to each element in nums)

    import numpy as np
    nums = [[1,2,3,4,5],
            [5,4,3,2,1]]
    
    nums_arr = np.array(nums)
    # Print second row of nums
    print(nums_arr[1,:])
    
    # Print all elements of nums that are greater than six
    print(nums_arr[nums_arr > 6])
    
    # Double every element of nums
    nums_dbl = nums_arr * 2
    print(nums_dbl)
    
    # Replace the third column of nums
    nums_arr[:,2] = nums_arr[:,2] + 1.12
    print(nums)