I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Querying a Series
Video: https://www.coursera.org/learn/python-data-analysis/lecture/3Fk9W/querying-a-series
Can query by index position (iloc) or index label (loc).
What does the term “broadcasting” mean in Pandas documentation?
https://stackoverflow.com/questions/29954263/what-does-the-term-broadcasting-mean-in-pandas-documentation
Can you write Python code for it?

import pandas as pd

student_classes = pd.Series(['Physics', 'Chemistry', 'English', 'History'], index = ['Alice', 'Jack', 'Molly', 'Sam'])
s = pd.Series(student_classes)
print(s)

print(s.iloc[3]) # index #3

print(s.loc['Molly']) # index 'Molly'

print(s[0])     # both work!
print(s['Alice'])

class_code = {99: 'Physics',
              100: 'Chemistry',
              101: 'English',
              102: 'History'}
# print(class_code[0]) # won't work in this case because indices are numbers
print(class_code[99]) # works

# iterate over list - long way

grades = pd.Series([90, 80, 70, 60])

total = 0
for grade in grades:
  total += grade
print(total/len(grades))

# iterate over list - better way

import numpy as np

total = np.sum(grades)
print(total / len(grades))

# Let's set up to time the different methods to show which is faster

numbers = pd.Series(np.random.randint(0, 1000, 10000))
print(len(numbers))
print(numbers.head())

%%timeit -n100

# iterative way

total = 0
for number in numbers:
  total += number
total / len(numbers)

%%timeit -n100

# better way - way faster! (uses numpy broadcasting)

total = np.sum(numbers)
total/len(numbers)

print(numbers.head())

# let's add 2 to all items
numbers += 2 # works fast on a np.Series!
print(numbers.head())

%%timeit n=10

# slow iterative approach

s = pd.Series(np.random.randint(0, 1000, 10000))
for label, value in s.iteritems():
  s.loc[label] = value + 2

%%timeit -n10

# waaaay faster way!

s = pd.Series(np.random.randint(0, 1000, 10000))
s += 2

s = pd.Series([1,2,3])
s.loc['History'] = 102 # add new index. Not a problem
print(s)

# unique indexes
students_classes = pd.Series({'Alice': 'Physics',
                              'Jack': 'Chemistry',
                              'Molly': 'English',
                              'Sam': 'History'})
print(student_classes)

# identtical indexes
kelly_classes = pd.Series(['Philosophy', 'Arts', 'Math'], index = ['Kelly', 'Kelly', 'Kelly'])
print(kelly_classes)

# merge the dissimilar Series - not a problem!
#...


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Regular Expression Operations Documentation
See https://docs.python.org/3/library/re.html
Regular Expressions Debugging
See https://regex101.com/
Week 2: Basic Data Processing with Pandas
Week 2: https://www.coursera.org/learn/python-data-analysis/home/week/2
Discussion Forum: https://www.coursera.org/learn/python-data-analysis/discussions/weeks/2
In this week of the course you'll learn the fundamentals of one of the most important toolkits Python has for data cleaning and processing -- pandas. You'll learn how to read in data into DataFrame structures, how to query these structures, and the details about such structures are indexed.
Learning Objectives
- Demonstrate how the series class builds on top of numpy datatypes
- Remember that the series class is a numpy array
- Demonstrate the basics of how to query a series structure
- Remember the dataframe as the principle data science structure
- Define the various features of a dataframe
- Demonstrate what an axis is in relation to dataframes
- Demonstrate the difference between the series and dataframe classes
- Create and use pandas DataFrames to represent raw data
Week 2 Reading Assignments
Course Textbook
Python for Data Analysis by Wes McKinney (O’Reilly). Copyright 2017 Wes McKinney, 978-1-491-95766-0.

Chapter Five: Getting started with pandas
Chapter Seven: Data Cleaning and Preparation

Introduction to Pandas
Video: https://www.coursera.org/learn/python-data-analysis/lecture/khJPQ/introduction-to-pandas
Stack Overflow Reference: https://stackoverflow.com/questions/tagged/pandas
Open Source, created in 2008 by Wes McKinney (the same author as the referece book)
See https://planetpython.org/
The Series Data Structure
Video: https://www.coursera.org/learn/python-data-analysis/lecture/lhVO7/the-series-data-structure
Can you write Python code for it?

import pandas as pd

students = ['Alice', 'Jack', 'Molly']
pd.Series(students)

numbers = [1, 2, 3]
pd.Series(numbers)

students = ['Alice', 'Jack', None]
pd.Series(students)

numbers = [1, 2, None]
pd.Series(numbers)

import numpy as np

print(np.nan == None) # False
print(np.nan == np.nan) # False (what?!! You can't do an equiality test to NaN...)
print(np.isnan(np.nan)) # True (this works this way)

import pandas as pd

student_scores = {'Alice': 'Physics',
                  'Jack': 'Chemistry',
                  'MOlly': 'English'}

s = pd.Series(student_scores)
print(s)

print(s.index)

students = [('Alice', 'Brown'), ('Jack', 'White'), ('Molly', 'Green')] # list of Tuples
print(pd.Series(students))

s = pd.Series(['Physics', 'Chemistry', 'English'], index = ['Alice', 'Jack', 'Molly'])
print(s)

# What happens when series doesn't agree with index? NaN
student_scores = {'Alice': 'Physics',
                  'Jack': 'Chemistry',
                  'Molly': 'English'}
s = pd.Series(student_scores, index = ['Alice', 'Molly', 'Sam'])
print(s)


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Strings can be split:
Can you write Python code for it?


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Summary
"Groupby is a powerful and commonly used tool for data cleaning and data analysis. Once you have grouped the data by some category you have a dataframe of just those values and you can conduct aggregated analsyis on the segments that you are interested. The groupby() function follows a split-apply-combine approach - first the data is split into subgroups, then you can apply some transformation, filtering, or aggregation, then the results are combined automatically by pandas for us."
Scales
Video: https://www.coursera.org/learn/python-data-analysis/lecture/sqXb4/scales
Types of scales:

ratio scales (units equally spaced, where mathematical operations are all valid. Height and width are examples.
interval scales (where 0 is data, not absense, such as temperature)
ordinal scales (grade letters A B etc.)
nominal scale (teams of a sport)
Can you write Python code for it?

# Ordinal example

import pandas as pd

df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
                  index=['excellent', 'excellent', 'excellent', 'good', 'good',
                         'good', 'ok', 'ok', 'ok', 'poor', 'poor'],
                  columns=["Grades"])
df.head()

df.dtypes

# let's change the object type to category

df["Grades"].astype("category").head()

# Let's use Pandas to make the data "ordered"

my_categories = pd.CategoricalDtype(categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],
                           ordered=True)
# use the astype() function
grades=df["Grades"].astype(my_categories)
grades.head()

# Prove that they're ordered

df[df['Grades'] > 'C']

# Re-read resources files from GitHub
!git clone https://github.com/pbeens/Coursera-Introduction-to-Data-Science-with-Python.git

import numpy as np
import pandas as pd

file = '/content/Coursera-Introduction-to-Data-Science-with-Python/resources/week-3/datasets/census.csv'
df = pd.read_csv(file)
df = df[df['SUMLEV'] == 50]
df = df.set_index('STNAME').groupby(level=0)['CENSUS2010POP'].agg(np.average)
df.head()

# Make bins using cut()

pd.cut(df,10)


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Summary
"Now you know how to merge and concatenate datasets together. You will find such functions very useful for combining data to get more complex or complicated results and to do analysis with. A solid understanding of how to merge data is absolutely essentially when you are procuring, cleaning, and manipulating data. It's worth knowing how to join different datasets quickly, and the different options you can use when joining datasets, and I would encourage you to check out the pandas docs for joining and concatenating data."
Pandas Idioms
Video: https://www.coursera.org/learn/python-data-analysis/lecture/iAJ8g/pandas-idioms
The "best" solutions are often referred to as idiomatic, especially in Python. Pandas also has idiomatic solutions, jokingly referred to as pandorable.
"Python programmers will often suggest that there many ways the language can be used to solve a particular problem. But that some are more appropriate than others. The best solutions are celebrated as Idiomatic Python and there are lots of great examples of this on StackOverflow and other websites.
A sort of sub-language within Python, Pandas has its own set of idioms. We've alluded to some of these already, such as using vectorization whenever possible, and not using iterative loops if you don't need to. Several developers and users within the Panda's community have used the term pandorable for these idioms. I think it's a great term. So, I wanted to share with you a couple of key features of how you can make your code pandorable."
Can you write Python code for it?

# In case we need to get the data again

!git clone https://github.com/pbeens/Coursera-Introduction-to-Data-Science-with-Python.git

census_data = '/content/Coursera-Introduction-to-Data-Science-with-Python/resources/week-3/datasets/census.csv'

import pandas as pd
import numpy as np
import timeit

df = pd.read_csv(census_data)
df.head()

# looking at chaining, first the pandorable method
# note the leading parenthisis to allow multiple lines for readability

(df.where(df['SUMLEV']==50)
  .dropna()
  .set_index(['STNAME', 'CTYNAME'])
  .rename(columns={'ESTMIMATESBASE2010': 'Estimates Base 2010'}))

# the "unpandorable" way

df = df[df['SUMLEV']==50]
df.set_index(['STNAME', 'CTYNAME'], inplace=True)
df.rename(columns={'ESTMIMATESBASE2010': 'Estimates Base 2010'})

# How do we know one approach is better? Let's time them.

def first_approach():
  global df
  return (df.where(df['SUMLEV']==50)
    .dropna()
    .set_index(['STNAME', 'CTYNAME'])
    .rename(columns={'ESTMIMATESBASE2010': 'Estimates Base 2010'}))

# re-read the data first
df = pd.read_csv(census_data)

# time it...
timeit.timeit(first_approach, number=10)

# Now the second approach

def second_approach():
  global df
  new_df = df[df['SUMLEV']==50]
  new_df.set_index(['STNAME', 'CTYNAME'], inplace=True)
  return new_df.rename(columns={'ESTMIMATESBASE2010': 'Estimates Base 2010'})

# re-read the data first
df = pd.read_csv(census_data)

# time it...
timeit.timeit(second_approach, number=10)

# Note that the "pandorable" (first) approach is much slower
# i.e. Sometimes the idiomatic approach is not better!

# Looking at another idiomatic approach using mapping/apply

# our helper function which returns a Series:
def min_max(row):
    data = row[['POPESTIMATE2010',
                'POPESTIMATE2011',
                'POPESTIMATE2012',
                'POPESTIMATE2013',
                'POPESTIMATE2014',
                'POPESTIMATE2015']]
    return pd.Series({'min': np.min(data), 'max': np.max(data)})

df.apply(min_max, axis='columns').head()

#...


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Summary
"So that's pivot tables. This has been a pretty short description, but they're incredibly useful when dealing with numeric data, especially if you're trying to summarize the data in some form. You'll regularly be creating new pivot tables on slices of data, whether you're exploring the data yourself or preparing data for others to report on. And of course, you can pass any function you want to the aggregate function, including those that you define yourself."
Date/Time Functionality
Video: https://www.coursera.org/learn/python-data-analysis/lecture/aIedN/date-time-functionality
"In today's lecture, where we'll be looking at the time series and date functionally in pandas. Manipulating dates and time is quite flexible in Pandas and thus allows us to conduct more analysis such as time series analysis, which we will talk about soon. Actually, pandas was originally created by Wed McKinney to handle date and time data when he worked as a consultant for hedge funds."
Experiments
Can you write Python code for it?

# Marquees are back! 😊
%%html
<marquee style='width: 50%; color: Green;'>Welcome to Tutorialspoint!</marquee>

import numpy as np

a = np.zeros([20,20])
b = np.ones([20,20])

print(a + b)


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Summary
"So there are a couple of Pandas idioms. But I think there's many more, and I haven't talked about them here. So here's an unofficial assignment for you. Go look at some of the top ranked questions on pandas on Stack Overflow, and look at how some of the more experienced authors, answer those questions. Do you see any interesting patterns? Feel free to share them with myself and others in the class."
Group by
Video: https://www.coursera.org/learn/python-data-analysis/lecture/EehvL/group-by
To help us understand aggregated data on a group level.
Can you write Python code for it?

# In case we need to get the data again

!git clone https://github.com/pbeens/Coursera-Introduction-to-Data-Science-with-Python.git

census_data = '/content/Coursera-Introduction-to-Data-Science-with-Python/resources/week-3/datasets/census.csv'

import pandas as pd
import numpy as np

df = pd.read_csv(census_data)
df = df[df['SUMLEV']==50] # filter the data
df.head()

# slow (iterative) approach to calc'ing average population

%%timeit -n2

df = pd.read_csv(census_data)

for state in df['STNAME'].unique():
  avg = np.average(df.where(df['STNAME']==state).dropna()['CENSUS2010POP'])
  print(f'{state}: avg population = {avg:.0f}.', end = " ")
print()

# another approach, using groupby() - much faster!

%%timeit -n2

df = pd.read_csv(census_data)

for group, frame in df.groupby('STNAME'): # returns a tuple with group (state) and DF
  avg = np.average(frame['CENSUS2010POP'])
  print(f'{group}: avg population = {avg:.0f}.', end = " ")
print()

#

df = pd.read_csv(census_data) # re-read the data

df = df.set_index('STNAME')

def set_batch_numer(item):
  if item[0] < 'M':
    return 0
  elif item[0] < 'Q':
    return 1
  else:
    return 2

for group, frame in df.groupby(set_batch_numer): # groupby() uses the index
  print(f'There are {len(frame)} records in group {group} for processing.')

# Using a different data file

file = '/content/Coursera-Introduction-to-Data-Science-with-Python/resources/week-3/datasets/listings.csv'
df = pd.read_csv(file)
df.head()

# grouping by two columns

# re-read file
df = pd.read_csv(file)

# set index so groupby() uses it
df=df.set_index(["cancellation_policy","review_scores_value"])

# When we have a multiindex we need to pass in the levels using level=(index_vals)
for group, frame in df.groupby(level=(0,1)):
    print(group)

# re-read file and set index of dataframe
df = pd.read_csv(file)
df=df.set_index(["cancellation_policy","review_scores_value"])

def grouping_fun(item):
  if item[1] == 10.0:
    return (item[0], '10.0')
  else:
    return (item[0], 'not 10.0')

for...


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Transformation
Can you write Python code for it?

# re-read and prep data
df = pd.read_csv(file)

cols = ['cancellation_policy', 'review_scores_value']

transform_df = df[cols].groupby('cancellation_policy').transform(np.nanmean)
transform_df.head()

# the above info is not very useful, so let's merge back with the original dataframe
# I'm not totally sure about what this example is demonstrating, especially with
# the groupby() in the previous cell. This was poorly explained, IMO.

transform_df.rename({'review_scores_value':'mean_review_scores'}, axis='columns', inplace=True)
df = df.merge(transform_df, left_index=True, right_index=True)
df.head()

# Looking at the difference between two columns and creating a new one

df['mean_diff']=np.absolute(df['review_scores_value']-df['mean_review_scores'])
df['mean_diff'].head()


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
Week 3: More Data Processing with Pandas
In this week you'll deepen your understanding of the python pandas library by learning how to merge DataFrames, generate summary tables, group data into logical pieces, and manipulate dates. We'll also refresh your understanding of scales of data, and discuss issues with creating metrics for analysis. The week ends with a more significant programming assignment.
Learning Objectives
- Create and use pandas DataFrames to represent raw data
Week 3 Reading Assignments
Course Textbook
Python for Data Analysis by Wes McKinney (O’Reilly). Copyright 2017 Wes McKinney, 978-1-491-95766-0.

Chapter Eight: Data Wrangling: Join, Combine, and Reshape
Chapter Ten: Data Aggregation and Group Operations
Chapter Twelve: Advanced pandas

Merging Dataframes
Video: https://www.coursera.org/learn/python-data-analysis/lecture/Kgwr5/merging-dataframes
Venn diagram terminology
- union (all)
- intersection (overlap)
Can you write Python code for it?

import pandas as pd

# First we create two DataFrames, staff and students.

staff_df = pd.DataFrame([{'Name': 'Kelly', 'Role': 'Director of HR'},
                        {'Name': 'Sally', 'Role': 'Course liasion'},
                        {'Name': 'James', 'Role': 'Grader'}])
# And lets index these staff by name
staff_df = staff_df.set_index('Name')

print(staff_df.head())

# Now we'll create a student dataframe
student_df = pd.DataFrame([{'Name': 'James', 'School': 'Business'},
                          {'Name': 'Mike', 'School': 'Law'},
                          {'Name': 'Sally', 'School': 'Engineering'}])
# Index by name as well
student_df = student_df.set_index('Name')

print(student_df.head())

# Let's merge ALL the data (union)
pd.merge(staff_df, student_df, how='outer', left_index=True, right_index=True)

# Note the NaN's

# Intersection - only records in both data sets

pd.merge(staff_df, student_df, how='inner', left_index=True, right_index=True)

# Left join (i.e., all staff members)

pd.merge(staff_df, student_df, how='left', left_index=True, right_index=True)

# Right join (i.e., all students)

pd.merge(staff_df, student_df, how='right', left_index=True, right_index=True)

# Column merge

# First, delete indexes
staff_df = staff_df.reset_index()
student_df = student_df.reset_index()

pd.merge(staff_df, student_df, how='right', on='Name')

# Watch when there are duplicate fields

staff_df = pd.DataFrame([{'Name': 'Kelly', 'Role': 'Director of HR',
                          'Location': 'State Street'},
                         {'Name': 'Sally', 'Role': 'Course liasion',
                          'Location': 'Washington Avenue'},
                         {'Name': 'James', 'Role': 'Grader',
                          'Location': 'Washington Avenue'}])
student_df = pd.DataFrame([{'Name': 'James', 'School': 'Business',
                            'Location': '1024 Billiard Avenue'},
                           {'Name': 'Mike', 'School': 'Law',
                            'Location': 'Fraternity House...


I am working on the file "Coursera_Introduction_to_Data_Science_with_Python.ipynb".
The first task is:
findall() and split()
Can you write Python code for it?

# findall() and split() return chunks

text = 'Amy works diligently. Amy gets good grades. Our student Amy is successful'
print(re.split('Amy', text)) # returns chunks split on 'Amy'
print(re.findall('Amy', text))
print(len(re.findall('Amy', text))) # number of occurrences


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
Histograms

In descriptive statistics, a histogram is a tool that precedes over to precursor methods such as dot plots on number line. It's a tool to visualize the frequency of a distribution.
In particular, Histograms are useful data visualziation tool for "Qunatitative data" in question.
Histogram concept:

Start off with number line, with data points superimposed respectively to there magnitude.

Next divide the line into equal chunks, called bins.

With each bin containing data points, we count the number of data points in each bin.

Finally, we draw a bar for each bin. The height of the bar corresponds to the number of data points that fall in this bin.

Go to top: TOC
Creating Histograms with Matplotlib

Importing convention:

import matplotlib.pyplot as plt

followed by calling the histogram func. using plt.

plt.hist(<list variable>, <no. of bins>)

Note: A good bit about the .hist() is, it automatically computes the boundries for all the bins. Also calculates how many values in each one.
Exercise 2

RQ1: What is a characteristic of a histogram?
Ans:

RQ2: You are working with a Python list with 10 different values. You divide the values into 5 equally-sized bins.
How wide will these bins be if the lowest value in your list is 0 and the highest is 20?
Ans:  The range of the values is 20, if we divide into 5 bins, then each bin will have a width of 4.
For a visual que, see below cell.
Can you write Python code for it?

x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 20]

import matplotlib.pyplot as plt

plt.hist( x, 5 )

plt.show()


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
Lab : Customization

Objective:
+ Customization of visual data.

Add

Labels

Title

Size

Ticks

Colour

Labeles:
You're going to work on the scatter plot with world development data: GDP per capita on the x-axis (logarithmic scale), life expectancy on the y-axis. The code for this plot is available in the script.
As a first step, let's add axis labels and a title to the plot. You can do this with the xlabel(), ylabel() and title() functions, available in matplotlib.pyplot. This sub-package is already imported as plt.

Instructions:

The strings xlab and ylab are already set for you. Use these variables to set the label of the x- and y-axis.

The string title is also coded for you. Use it to add a title to the plot.

After these customizations, finish the script with plt.show() to actually display the plot.
Can you write Python code for it?

# Basic scatter plot, log scale
# plt.scatter(gdp_cap, life_exp)
# plt.xscale('log')

# Strings
# xlab = 'GDP per Capita [in USD]'
# ylab = 'Life Expectancy [in years]'
# title = 'World Development in 2007'

# Add axis labels
# plt.xlabel(xlab)
# plt.ylabel(ylab)

# Add title
# plt.title(title)

# After customizing, display the plot
# plt.show()


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
Line Plot 2

Question: What is the first year in which there will be more than ten billion human beings on this planet?
Ans: By 2060, the world population will rise appx. to 10 billion.

Go to top: TOC
Line plot 3

Preface:
Now that you've built your first line plot, let's start working on the data that professor Hans Rosling used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you:

life_exp which contains the life expectancy for each country and

gdp_cap, which contains the GDP per capita, for each country expressed in US Dollar.

GDP stands for Gross Domestic Product. It basically represents the size of the economy of a country.Divide this by the population and you get the GDP per capita.

Instructions:

Print the last item from both the list gdp_cap, and the list life_exp; it is information about Zimbabwe.

Build a line chart, with gdp_cap on the x-axis, and life_exp on the y-axis.

Does it make sense to plot this data on a line plot?

Don't forget to finish off with a plt.show() command, to actually display the plot.

Go to top: TOC
Can you write Python code for it?

# Print the last item of gdp_cap and life_exp
# print( gdp_cap[ -1 ] )
# print( life_exp[ -1 ])

# Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis
# plt.plot( gdp_cap, life_exp )

# Display the plot
# plt.show()


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
RQ3: You write the following code:
```
import matplotlib.pyplot as plt
x = [1, 3, 6, 3, 2, 7, 3, 9, 7, 5, 2, 4]
plt.hist(x)
plt.show()```

You need to extend the plt.hist() command to specifically set the number of bins to 4. What should you do?
Ans:  plt.hist(x, 4)

Go to top: TOC
Lab histograms

Objective:

Experiment with histograms.

Work with different bins.

Work with dfferent datasets.

Lab exercises:

Build a histogram 1

Build a histogram 2 : bins

Build a histogram 3 : compare

Choose the right plot 1.

Chosse the right plot 2.

Go to top: TOC
Build a  histogram 1.

Preface:
life_exp, the list containing data on the life expentancy for different countries in 2007(at data camp only!)
To see how life expectancy in different countries is distributed, let's create a histogram of life_exp.
Instructions:

Use plt.hist() to create a histogram of the values in life_exp.

Do not specify the number of bins; Python will set the number of bins to 10 by default for you.

Add plt.show() to actually display the histogram. Can you tell which bin contains the most observations?

```
Create histogram of life_exp data
plt.hist(life_exp)
Display histogram
plt.show()
```

Go to top: TOC
Build a histogram 2 : bins

By default python sets the number of bins to 10.

Number of bins is important,

Can zoom in / out of the data.

zooming in : shows much more detail, but not the bigger picture.

zooming out : shows the bigger picture.

To control the no. of bins to divide your data in,
- by setting the `bins` argument.

Preface:
We'll be makin two plots here.

Use plt.clf() to clean up again to start fresh.

Instructions:

Build a histogram of life_exp, with 5 bins.

Can you tell which bins contains the most observations?

Build another histogram of life_exp, this time with 20 bins.

Is this better?

Go to top: TOC
Can you write Python code for it?

# Build histogram with 5 bins
    # Ans: plt.hist(life_exp, bins = 5)
    # 4th and 5th bins.

# Show and clean up plot
# plt.show()
# plt.clf()

# Build histogram with 20 bins
# Ans: plt.hist( life_exp, bins = 20 )
    # Much better, 15th bin contains maximum value,
    # i.e. most people tend to live upto 71-73 years.

# Show and clean up again
    # plt.show()
    # plt.clf()


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
Scatter Plot 1

It's fine to use such tools, but how do we know which one is best suited for which purpose? As a rule of thumb:

When we have a time scale along the horizontal axis.

We generally prefer a line plot.

When we're trying to assess if there's a correlation b/w two variables.

We go with scatter plot.

Importing convention:
import matplotlib.pyplot as plt
    plt.scatter( x, y )
    plt.show()
Preface:
Let's continue with the gdp_cap versus life_exp plot, the GDP and life expectancy data for different countries in 2007. Maybe a scatter plot will be a better alternative?
Instructions:

Change the line plot that's coded in the script to a scatter plot.

A correlation will become clear when you display the GDP per capita on a logarithmic scale. Add the line plt.xscale('log').

Finish off your script with plt.show() to display the plot.

Go to top: TOC
Can you write Python code for it?

# Change the line plot below to a scatter plot
#plt.scatter(gdp_cap, life_exp)

# Put the x-axis on a logarithmic scale
#plt.xscale('log')

# Show plot
#plt.show()


I am working on the file "Courses/DAT-208x/.ipynb_checkpoints/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib-checkpoint.ipynb".
The first task is:
Scatter Plot 2

Preface:
In the previous exercise, you saw that that the higher GDP usually corresponds to a higher life expectancy. In other words, there is a positive correlation.
Do you think there's a relationship between population and life expectancy of a country?

Instructions:

Start from scratch: import matplotlib.pyplot as plt.

Build a scatter plot, where pop is mapped on the horizontal axis, and life_exp is mapped on the vertical axis.

Finish the script with plt.show() to actually display the plot. Do you see a correlation?

Go to top: TOC
Can you write Python code for it?

# Import package
# import matplotlib.pyplot as plt

# Build Scatter plot
# plt.scatter( pop, life_exp )

# Show plot
# plt.show()

"""Conclusion: Ther's no correlation b/w population
and Life Expectency! Which makes perfect sense."""


I am working on the file "Courses/DAT-208x/DAT-208x-Week2-Section3-Manipulating-Python-List.ipynb".
The first task is:
2. Extend a list -- 100xp, status:

Concept: We can add elements to a list by using a + operator.

Syntax : listA = listB + [ elem1, elem2, elem3, ... , elem(n-1) ]
Can you write Python code for it?

"""
Problem Definiton:

You just won the lottery, awesome! You decide to build a poolhouse and a garage.
Can you add the information to the areas list?

Instructions:

    + Use the + operator to paste the list ["poolhouse", 24.5] to the end of
      the "areas" list. Store the resulting list as "areas_1".

    + Further extend "areas_1" by adding data on your garage.
      Add the string "garage" and float "15.45".
      Name the resulting list "areas_2".

"""

# Create the areas list and make some changes
areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0,
         "bedroom", 10.75, "bathroom", 10.50]

# Add poolhouse data to areas, new list is areas_1
areas_1 = areas + [ "poolhouse", 24.5 ]

# Add garage data to areas_1, new list is areas_2
areas_2 = areas_1 + [ "garage", 15.45 ]


I am working on the file "Courses/DAT-208x/DAT-208x-Week2-Section3-Manipulating-Python-List.ipynb".
The first task is:
3. Delete a list element -- 50xp, status:

Concept: We can "delete" elements from a an existing list using a del statement.

Syntax: del( list_name[ element_index ] )

Note: After deleting an element from a list, the indexes of all the elements after the deleted item change!
Can you write Python code for it?

"""
Problem Definition:

There was a mistake! The amount you won with the lottery is not that big
after all and it looks like the poolhouse isn't going to happen.
You decide to remove the corresponding string and float from the areas list.

The ; sign is used to place commands on the same line.
The following two code chunks are equivalent:

        + command1; command2   # Same line

        + command1             # Seperate line
          command2

Which of the code chuks will do the job for us?

        Ans: del( areas[ -4 : -2 ] )
"""


I am working on the file "Courses/DAT-208x/DAT-208x-Week2-Section3-Manipulating-Python-List.ipynb".
The first task is:
4. Inner Working of lists -- 100xp, status:
Can you write Python code for it?

"""
Problem Definition:

    + "areas" list already exist in the code, with it's copy, "areas_copy".

    + Next, 1st element in the "areas_copy" list is changed, and "areas" pirnted out.

    + If we make a change to the "copy", it will affect the "orginal list" too.

        - That's because, although the list being different, they have the same
          "reference" to the list!

    + To avoid this situation, we have to make an "explicit copy" of "areas"
      list.

    + Using "list()" or [ : ]

        ------------------------------------------------------------

Instructions:

    + Change the second command, that creates the variable areas_copy,

        - such that "areas_copy" is an explicit copy of the "areas".

    + Now, changes made to "areas_copy", shouldn't affect the areas.

"""
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Create areas_copy
areas_copy = list( areas )  # converting areas to an explicit list

# Change areas_copy
areas_copy[0] = 5.0

# Print areas
print("Original list: " + str(areas))
print("Explicit copy: " + str(areas_copy))


I am working on the file "Courses/DAT-208x/DAT208X - Week 2 - Section 2 - Subsetting Lists.ipynb".
The first task is:
**5. Subsetting lists of lists

We can subset "lists of lists".

Syntax: list[ [ sub-list1 ], [sub-list2], ... , [sub-list(n-1)] ]
                      0            1                     n-1

We can also perform both, "indexing" and "slicing" on a "lists of lists".

Syntax: list[ < sub-list-index > ] [ < begin > : < end > ]
Can you write Python code for it?

"""
Problem definition: What will house[-1][1] return?

"""

# Ans : float, 9.5 as the bathroom area.


I am working on the file "Courses/DAT-208x/DAT208X - Week 2 - Section 2 - Subsetting Lists.ipynb".
The first task is:
3. Slicing and dicing

Slicing means selecting multiple elemens from our list.

It's like splitting a list into sub-list.
Can you write Python code for it?

"""
Instructions:

    + Use slicing to create a list, "downstairs", that contains the first
      6 elements of "areas".

    + Do a similar thing to create a new variable, "upstairs", that contains
      the last 4 elements of areas.

    + Print both "downstairs" and "upstairs" using print().

"""

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
         10.75, "bathroom", 9.50]

# Use slicing to create downstairs
downstairs = areas[0:7]

# Use slicing to create upstairs
upstairs = areas[6:]

# Print out downstairs and upstairs
print( downstairs )

print( upstairs )


I am working on the file "Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb".
The first task is:
2. Baseball player's height

Preface:
You are a huge baseball fan. You decide to call the MLB (Major League Baseball) and ask around for some more statistics on the height of the main players. They pass along data on more than a thousand players, which is stored as a regular Python list: height. The height is expressed in inches. Can you make a Numpy array out of it and convert the units to centimeters?
Can you write Python code for it?

"""
Instructions:

    + Create a Numpy array from height. Name this new array np_height.

    + Print "np_height".

    + Multiply "np_height" with 0.0254 to convert all height measurements from inches to meters.

        - Store the new values in a new array, "np_height_m".

    + Print out np_height_m and check if the output makes sense.

"""

# height is available as a regular list
# http://wiki.stat.ucla.edu/socr/index.php/SOCR_Data_MLB_HeightsWeights#References

# Import numpy
import numpy as np

# Create a Numpy array from height: np_height
np_height = np.array( height )

# Print out np_height
print("The Height of the baseball players are: " + str( np_height ) )

# Convert np_height to m: np_height_m
np_height_m = np_height * 0.0254   # a inch is 0.0245 meters

# Print np_height_m
print("\nThe Height of the baseball players in meters are: " + str( np_height_m ) )


I am working on the file "Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb".
The first task is:
3. Baseball player's BMI:

Preface:
The MLB also offers to let you analyze their weight data. Again, both are available as regular Python lists: height and weight. height is in inches and weight is in pounds.
It's now possible to calculate the BMI of each baseball player. Python code to convert height to a Numpy array with the correct units is already available in the workspace. Follow the instructions step by step and finish the game!
Can you write Python code for it?

"""
Instructions:

    + Create a Numpy array from the weight list with the correct units.

        -  Multiply by 0.453592 to go from pounds to kilograms.

        - Store the resulting Numpy array as np_weight_kg.

    + Use np_height_m and np_weight_kg to calculate the BMI of each player.

        - Use the following equation:

          BMI = weight( kg ) / height( m )

        - Save the resulting numpy array as "bmi".

    + Print out "bmi".

"""
# height and weight are available as a regular lists

# Import numpy
import numpy as np

# Create array from height with correct units: np_height_m
np_height_m = np.array(height) * 0.0254

# Create array from weight with correct units: np_weight_kg
np_weight_kg = np.array( weight ) * 0.453592

# Calculate the BMI: bmi
bmi = np_weight_kg / np_height_m ** 2

# Print out bmi
print("\nThe Bmi of all the baseball players are: " + str( bmi ) )


I am working on the file "Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb".
The first task is:
Note:

Numpy assumes that your array contain elements of same type.

If the arary contains elements of differnet types, then resulitng numpy array will converted to type string.

Numpy array should'nt be missclassified as an array, technically it a "new data type", just like int, string, float or boolean, and:

Comes packaged with it's own methods.

i.e. It can behave differently than you'd expect.
Can you write Python code for it?

# A numpy arary with different types
np.array( [1, 2.5, "are different", True ] )


I am working on the file "Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb".
The first task is:
Numpy : remarks
Can you write Python code for it?

# a simple python list
py_list = [ 1, 2, 3 ]

# a numpy array
numpy_array = np.array([1, 2, 3])

"""
remarks:

+ If we add py_list with itself, it will generate a list of
  new length.

+ Whereas, if we add the numpy_array, it would perform,
  "element wise addition"

Warning:

Again be careful while using different python types in a numpy arary.

"""
py_list + py_list

numpy_array + numpy_array


I am working on the file "Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb".
The first task is:
Numpy Subsetting

All the subsetting operation on a list, also get's performed on
Numpy arrays, except for a few minor change, we look them now.
Can you write Python code for it?

bmi

# get the fourth elemnt from the numpy array "bmi"
print("The bmi of the fourth element is: " + str( bmi[3] ) )

# slice and dice
print("\nThe bmi's from 2nd to 3rd element is: " + str( bmi[2 : 4] ) )

"""

    Specifically for Numpy, there's another way to do list
    subsetting via "booleans", here's how.

"""

print("\nList of bmi have bmi larger than 23: " + str( bmi > 23 ) )

# Next, use this boolean arary to do subsetting

print("\nThe element with the largest bmi is: " + str(bmi[ bmi > 23 ]) )


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Additional Customizations:

Preface:
If you have another look at the script, under # Additional Customizations, you'll see that there are two plt.text() functions now. They add the words "India" and "China" in the plot.
Instructions:

Add plt.grid(True) after the plt.text() calls so that gridlines are drawn on the plot.

Go to top
Can you write Python code for it?

"""# Scatter plot
plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c = col, alpha = 0.8)

# Previous customizations
plt.xscale('log')
plt.xlabel('GDP per Capita [in USD]')
plt.ylabel('Life Expectancy [in years]')
plt.title('World Development in 2007')
plt.xticks([1000,10000,100000], ['1k','10k','100k'])

# Additional customizations
plt.text(1550, 71, 'India')
plt.text(5700, 80, 'China')

# Add grid() call
plt.grid(True)

# Show the plot
plt.show()
"""


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Colors:

Preface:
Let's make our plot more colorful.

col is a list with a color for each corresponding country, depending on the continent the country is part of.

How did we make the list col?

We define a dictionary containing a list of continent as "keys" mapped to "colors" as "values".

dict = {
        'Asia':'red',
        'Europe':'green',
        'Africa':'blue',
        'Americas':'yellow',
        'Oceania':'black'
    }

Instructions:

Add c = col to the arguments of the plt.scatter() function.

Change the opacity of the bubbles by setting the alpha argument to 0.8 inside plt.scatter(). Alpha can be set from zero to one, where zero totally transparant, and one is not transparant.

Go to top
Can you write Python code for it?

"""
# Specify c and alpha inside plt.scatter()
plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c = col, alpha= 0.8)

# Previous customizations
plt.xscale('log')
plt.xlabel('GDP per Capita [in USD]')
plt.ylabel('Life Expectancy [in years]')
plt.title('World Development in 2007')
plt.xticks([1000,10000,100000], ['1k','10k','100k'])

# Show the plot
plt.show()
"""


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Lab : Customization

Objective:
+ Customization of visual data.

Add

Labels

Title

Size

Ticks

Colour

Additional Customizations

Labels:
You're going to work on the scatter plot with world development data: GDP per capita on the x-axis (logarithmic scale), life expectancy on the y-axis. The code for this plot is available in the script.
As a first step, let's add axis labels and a title to the plot. You can do this with the xlabel(), ylabel() and title() functions, available in matplotlib.pyplot. This sub-package is already imported as plt.

Instructions:

The strings xlab and ylab are already set for you. Use these variables to set the label of the x- and y-axis.

The string title is also coded for you. Use it to add a title to the plot.

After these customizations, finish the script with plt.show() to actually display the plot.
Can you write Python code for it?

# Basic scatter plot, log scale
# plt.scatter(gdp_cap, life_exp)
# plt.xscale('log')

# Strings
# xlab = 'GDP per Capita [in USD]'
# ylab = 'Life Expectancy [in years]'
# title = 'World Development in 2007'

# Add axis labels
# plt.xlabel(xlab)
# plt.ylabel(ylab)

# Add title
# plt.title(title)

# After customizing, display the plot
# plt.show()


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Line Plot 2

Question: What is the first year in which there will be more than ten billion human beings on this planet?
Ans: By 2060, the world population will rise appx. to 10 billion.

Go to top: TOC
Line plot 3

Preface:
Now that you've built your first line plot, let's start working on the data that professor Hans Rosling used to build his beautiful bubble chart. It was collected in 2007. Two lists are available for you:

life_exp which contains the life expectancy for each country and

gdp_cap, which contains the GDP per capita, for each country expressed in US Dollar.

GDP stands for Gross Domestic Product. It basically represents the size of the economy of a country.Divide this by the population and you get the GDP per capita.

Instructions:

Print the last item from both the list gdp_cap, and the list life_exp; it is information about Zimbabwe.

Build a line chart, with gdp_cap on the x-axis, and life_exp on the y-axis.

Does it make sense to plot this data on a line plot?

Don't forget to finish off with a plt.show() command, to actually display the plot.

Go to top: TOC
Can you write Python code for it?

# Print the last item of gdp_cap and life_exp
# print( gdp_cap[ -1 ] )
# print( life_exp[ -1 ])

# Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis
# plt.plot( gdp_cap, life_exp )

# Display the plot
# plt.show()


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
RQ3: You write the following code:
```
import matplotlib.pyplot as plt
x = [1, 3, 6, 3, 2, 7, 3, 9, 7, 5, 2, 4]
plt.hist(x)
plt.show()```

You need to extend the plt.hist() command to specifically set the number of bins to 4. What should you do?
Ans:  plt.hist(x, 4)

Go to top: TOC
Lab histograms

Objective:

Experiment with histograms.

Work with different bins.

Work with dfferent datasets.

Lab exercises:

Build a histogram 1

Build a histogram 2 : bins

Build a histogram 3 : compare

Choose the right plot 1.

Chosse the right plot 2.

Go to top: TOC
Build a  histogram 1.

Preface:
life_exp, the list containing data on the life expentancy for different countries in 2007(at data camp only!)
To see how life expectancy in different countries is distributed, let's create a histogram of life_exp.
Instructions:

Use plt.hist() to create a histogram of the values in life_exp.

Do not specify the number of bins; Python will set the number of bins to 10 by default for you.

Add plt.show() to actually display the histogram. Can you tell which bin contains the most observations?

```
Create histogram of life_exp data
plt.hist(life_exp)
Display histogram
plt.show()
```

Go to top: TOC
Build a histogram 2 : bins

By default python sets the number of bins to 10.

Number of bins is important,

Can zoom in / out of the data.

zooming in : shows much more detail, but not the bigger picture.

zooming out : shows the bigger picture.

To control the no. of bins to divide your data in,
- by setting the `bins` argument.

Preface:
We'll be makin two plots here.

Use plt.clf() to clean up again to start fresh.

Instructions:

Build a histogram of life_exp, with 5 bins.

Can you tell which bins contains the most observations?

Build another histogram of life_exp, this time with 20 bins.

Is this better?

Go to top: TOC
Can you write Python code for it?

# Build histogram with 5 bins
    # Ans: plt.hist(life_exp, bins = 5)
    # 4th and 5th bins.

# Show and clean up plot
# plt.show()
# plt.clf()

# Build histogram with 20 bins
# Ans: plt.hist( life_exp, bins = 20 )
    # Much better, 15th bin contains maximum value,
    # i.e. most people tend to live upto 71-73 years.

# Show and clean up again
    # plt.show()
    # plt.clf()


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Scatter Plot 2

Preface:
In the previous exercise, you saw that that the higher GDP usually corresponds to a higher life expectancy. In other words, there is a positive correlation.
Do you think there's a relationship between population and life expectancy of a country?

Instructions:

Start from scratch: import matplotlib.pyplot as plt.

Build a scatter plot, where pop is mapped on the horizontal axis, and life_exp is mapped on the vertical axis.

Finish the script with plt.show() to actually display the plot. Do you see a correlation?

Go to top: TOC
Can you write Python code for it?


I am working on the file "Courses/DAT-208x/DAT208X - Week 5 - Section 1 - Plotting_with_MatplotLib.ipynb".
The first task is:
Sizes:

Preface: Our scatter plot at present is just a cloud of blue dots, indistinguishable from each other. We can represent the size of the dots corresponds to the population.

pop is a list of population numbers for each country expressed in millions.

s is an argument scatter method as the argument for size.

Instructions:

Run the script to see how th plot changes.

Increase the size of bubbles to emphesize them more.

Import numpy package as np.

Use np.array() to create a numpy array from the list pop. Call this Numpy array np_pop.

Double the values in np_pop by assigning np_pop * 2 to np_pop again.

Because np_pop is a numpy array, each array element will be doubled.

Change the s argument inside plt.scatter() to be np_pop instead of pop.

Go to top
Can you write Python code for it?

# Import numpy as np
# import numpy as np

# Store pop as a numpy array: np_pop
# np_pop = np.array(pop)

# Double np_pop
# np_pop *= 2

# Update: set s argument to np_pop
# plt.scatter(gdp_cap, life_exp, s = np_pop)

# Previous customizations
# plt.xscale('log')
# plt.xlabel('GDP per Capita [in USD]')
# plt.ylabel('Life Expectancy [in years]')
# plt.title('World Development in 2007')
# plt.xticks([1000, 10000, 100000],['1k', '10k', '100k'])

# Display the plot
# plt.show()


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
3. Other variable types
In the previous exercise, you worked with two Python data types:

int, or integer: a number without a fractional part.
savings, with the value 100, is an example of an integer.

float, or floating point: a number that has both an integer and fractional part, separated by a point. factor, with the value 1.10, is an example of a float.

Next to numerical data types, there are two other very common data types:

str, or string: a type to represent text. You can use single or double quotes to build a string.

bool, or boolean: a type to represent logical values. Can only be True or False.
Can you write Python code for it?

"""
Instructions :

    * Create a new string, 'desc', with the value "compound interest".

    * Create a new boolean, 'profitable', with the value 'True'.

"""

# Create a variable desc
desc = "compound interest"

# Create a variable profitable
profitable = True


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
4. Guess the type
To find out the type of a value or a variable that refers to that value, you can use the type() function. Suppose you've defined a variable a, but you forgot the type of this variable. To determine the type of `a, simply execute:
type(a)
Can you write Python code for it?

a = 10.21
b = "Python's fun!"
c = False

# Check there types:

type(a)

type(b)

type(c)


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
6. Type conversion
Using the + operator to paste together two strings can be very useful in building custom messages.
Suppose for example that you've calculated the return of your investment, and want to summarize the results in a string. Assuming the floats savings and result are defined, you can try something like this:
print("I started with $" + savings + " and now have $" + result + ". Awesome!")
note: But we cannot sum strings and floats, so above code will return an error.
To fix the error:

Need to explicitly convert the types of your variables.

Use a str() to convert a value into a string.

Similerly, use int(), float and bool() for desired conversion types.
Can you write Python code for it?

"""
Instructions:

    + First run the code, and identify the errors.

    + Next, fix those errors by appropritate type conversion functions.

    + Convert variable 'pi_string' --> 'float', as a new variable 'pi_float'.

"""
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7

# Fix the printout
print("I started with $" + savings + " and now have $" + result + ". Awesome!")

# Definition of pi_string
pi_string = "3.1415926"

# Convert pi_string into float: pi_float

# Fixed code
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7

# Fix the printout
print("I started with $" + str( savings ) + " and now have $" + str( result ) + ". Awesome!")

# Definition of pi_string
pi_string = "3.1415926"

# Convert pi_string into float: pi_float
pi_float = float(pi_string)


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
7. Can Python handle everything?
Following are some code snipptes, try to find which one is correct:

"I can add integers, like" + str(5) + "to strings."

"I said " + ("Hey " * 2) + "Hey!"

"The correct answer to this multiple choice exercise is answer number " + 2

True + False
Can you write Python code for it?

print( "I can add integers, like " + str(5) + " to strings." )

print( "I said " + ("Hey " * 2) + "Hey!" )

# Error
("The correct answer to this multiple choice exercise is answer number " + 2)

print( True + False )


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
Lecture : Variables and Types

[RQ1] : Which line of code creates a variable x with the value '15'?
Ans: x = 15 ( inline code used ).

[RQ2] :  What is the value of the variable z after executing these commands?
x = 15
y = 7
z = x + y + 1
Ans: 13

[RQ3] :  You execute the following two lines of Python code:
x = "test"
y = False
Ans: x is a string, and y is a boolean.

Lab : Variables and Types

Objective:

Creating Variables.
Performing Calculations on them.
Understand different data types that python offers.

Variable Assignment, earned credit : 100xp

Calculations with variables, earned credit : 100xp

Other variable types, earned credit : 100xp

Guess the type, earned credit : 50xp

Operations with the other types, earned credit : 100xp

Type conversion, earned credit : 100xp

Can Python handle everything?, earned credit : 50xp

1. Variable Assignment
In Python, a variable allows you to refer to a value with a name. To create a variable use =, like this example:
x = 5
You can now use the name of this varibale x, instead of the actual value, 5.
Can you write Python code for it?

"""
    Instructions :

    * Create a variable savings with the value 100.

    * Check out this variable by typing 'print( savings )` in the script.

"""

# Create a variable savings
savings = 100

# Print out savings
print("savings: ", savings )


I am working on the file "Courses/DAT-208x/DAT208x - Week 1 - Python Basics.ipynb".
The first task is:
Python as a calculator -- 100xp, Status : Earned

Python is perfectly suited to do basic calculations. Apart from addition, subtraction, multiplication and division, there is also support for more advanced operations such as:

Exponentiation:. This operator raises the number to its left to the power of the number to its right: for example 42 will give 16.

Modulo: %. It returns the remainder of the division of the number to the left by the number on its right, for example 18 % 7 equals 4.
Can you write Python code for it?

"""Suppose you have $100, which you can invest with a 10% return each year. After one year, it's
100 x 1.1 = 110 dollars, and after two years it's 100 x 1.1 x 1.1 = 121.

Add code to calculate how much money you end up with after 7 years"""

print(5 + 5)
print(5 - 5)

# Multiplication and division
print(3 * 5)
print(10 / 2)

# Exponentiation
print(4 ** 2)

# Modulo
print(18 % 7)

# How much is your $100 worth after 7 years?
# first try was unsuccesful, so used the only two things * and ** operators.
print ( 100 * ( 1.1 ** 7 ) )


I am working on the file "Courses/DAT-208x/DAT208x - Week 2 - Section 1- Python List data strucuture.ipynb".
The first task is:
2. Creating list with different types - 100xp, Status : Earned

A list can contain any Python type and a mix of Python types as well.
variable = [ <int>, <float>, <str>, <list> ]
Can you write Python code for it?

"""
Problem summary:

   The code on the right is the start of a solution. For some of the areas,
   the name of the corresponding room is already placed in front. Pay attention here!
   "bathroom" is a string, while bath is a variable that represents the float 9.50 you specified earlier.

Instruction:

    + Create the "areas" list such that,

        - List first contains the name of each room as a string,
          and then its area.

        - More specifically, add the strings "hallway", "kitchen" and "bedroom"
          at the appropriate locations.

    + Print "areas" again; is the printout more informative this time?

"""

# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50

# Adapt list areas
areas = ["hallway", hall,"kitchen", kit, "living room", liv, "bedroom", bed, "bathroom", bath]

# Print areas
print(areas)


I am working on the file "Courses/DAT-208x/DAT208x - Week 2 - Section 1- Python List data strucuture.ipynb".
The first task is:
3. Select the valid list -- 50xp, status : Earned

List is also a Python type.

Meaning, list can selfcontain a list! Or a sub-list.

Syntax : variable_name = [ elem1, elem2, elem3 ... ,elem(n -1) ]

Can you tell which ones of the following lines of Python code are valid ways to build a list?_
A) `[ 1, 3, 4, 2 ]`

B) `[ [ 1, 2, 3 ], [ 4, 5, 7 ] ]`

C) `[ 1 + 2, "a" * 5, 3 ]`

Ans:  All of them.
Can you write Python code for it?

list1 = [ [ 1, 2, 3 ], [ 4, 5, 7 ] ]

list2 = [ 1 + 2, "a" * 5, 3 ]

# print the list to check any errors

print( list1 )

print( list2 )


I am working on the file "Courses/DAT-208x/DAT208x - Week 2 - Section 1- Python List data strucuture.ipynb".
The first task is:
4 List of Lists -- 100xp, status: Earned
Can you write Python code for it?

"""
Problem summary:

    As a data scientist, you'll often be dealing with a lot of data,
    and it will make sense to group some of this data.

    Instead of creating a flat list containing strings and floats,
    representing the names and areas of the rooms in your house,
    you can create a list of lists. The script on the right can already give you an idea.

    Don't get confused here: "hallway" is a string,
    while hall is a variable that represents the float 11.25 you specified earlier.

Instructions:

    + Finish the list of lists so that it also contains the bedroom and bathroom data.

        - Make sure you enter these in order!

    + Print out "house";

        - Dows this way of structuring your data make more sense?

    + Printt out the type of "house".

        - Are you still dealing with a list?

"""

# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50

# house information as list of lists
house = [ ["hallway", hall],
          ["kitchen", kit],
          ["living room", liv],
          ["bedroom", bed],
          ["bathroom", bath] ]

# Print out house
print( house )

# Print out the type of house
print( type( house ) )


I am working on the file "Courses/DAT-208x/DAT208x - Week 3 - Section 1 - Functions.ipynb".
The first task is:
What if while using max()there were multiple items?

In this case, the function returns the first one encountered. This remains consistent with other sort-stability preserving tools, such as sorted() and heapq().

Exercise:

1) RQ1: What is a Python function?
Ans: A piece of reusable Python code, that solves a particular problem.
2) RQ2: You have a list named x. To calculate the minimum value in this list, you use the min() function.
Which Python command should you use?
Ans: min(x)
3) RQ3: What Python command opens up the documentation from inside the IPython Shell for the min fucntion?
Ans: help(min)
4) RQ4: The function round has two arguments. Select the two correct statements about these arguments.
Ans: Number is a required argument, and ndigits is an optional argument.
Lab: Functions

Objective:

Use functions in different ways.

Experiment with different ways of specifyinng arguments.

How default argumetns work.

1 Familiar functions - 100xp, status: Earned

The genereal recepie for calling functions is:
`output = function_name(input)`

                 or

`variable = function_name( required arg, [ optional arg ] )`
Can you write Python code for it?

"""
Instructionns:

        + Use print() in combination with type() to print out the type of
        var1.

        + Use len() to get the length of the list var1.
          Wrap it in a print() call to directly print it out.

        + Use int() to convert var2 to an integer. Store the output as out2.
"""

# Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True

# Print out type of var1
print( type( var1 ) )

# Print out length of var1
print( len( var1 ))

# Convert var2 to an integer: out2
out2 = int( var2 )
print(out2)


I am working on the file "Courses/DAT-208x/DAT208x - Week 3 - Section 2 - Methods.ipynb".
The first task is:
2. List Methods -- 100xp, status: earned
Other Python data types alos have many common method's associated with them, some of these methods are exclusive to some data types.
A few of them we will be experimenting on them:

index(), to get the index of the first element of a slist that matches its input.

count(), to get the number of times an element appears in a list.
Can you write Python code for it?

"""
Instructions:

    + Use the index() method to get the index of the element
      in areas that is equal to 20.0. Print out this index.

    + Call count() on areas to find out how many times 14.5
      appears in the list. Again, simply print out this number.

"""
# first let's look more about these methods
help(str.count)
print(2*"\n===================================================")
help(str.index)
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Print out the index of the element 20.0
print( "\nThe index of the element 20.0 is: " + str( areas.index( 20 ) ) )

# Print out how often 14.5 appears in areas
print("\nThe number of times 14.5 occurs is: " + str( areas.count( 14.5 ) ) )


I am working on the file "Courses/DAT-208x/DAT208x - Week 3 - Section 2 - Methods.ipynb".
The first task is:
3. List Methods II -- 100xp, status: earned

Most list methods will change the list they're called on. E.g.

append() : adds and element to the list it is called on.

remove(): removes the "1st element" of a list that matches the inuput.

reverse() : reverse the order of the elements in the list it is called on.
Can you write Python code for it?

"""
Instructions:

    + Use the append method twice to add the size of the
      poolhouse and the garage again:

          - 24.5 and 15.45, respectively.

          - Add them in order

   + Print out the areas.

   + Use the reverse() method to reverse the order of the
     elements in areas.

   + Print out the area once more.
"""
# Let's look at the help on these methods
help( list.append )
print("=====================================================")
help( list.remove )
print("=====================================================")
help( list.reverse )

# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Use append twice to add poolhouse and garage size
areas.append( 24.5 )
areas.append( 15.45 )

# Print out areas
print("\nThe new list contains two new items: " + str( areas )  )

# Reverse the orders of the elements in areas
areas.reverse()

# Print out areas
print("\nThe new list has been reversed: " + str( areas ) )


I am working on the file "Courses/DAT-208x/DAT208x - Week 3 - Section 3 - Python Packages.ipynb".
The first task is:
2) Selective import:

General package import statement, import < package name >

Selective pacakge import statement,
from < package name > import < function, method, type or constant >
Can you write Python code for it?

"""
Instructions :

    + Perform a selective import from the "math" package where,
      you only import the "radians" function.

    + Cal:

        - Distance travelled by the Moon over 12 degrees of its orbit.

        - Assign the result to "dist".

        - calculate this as r ∗ ϕ,
          where r is the radius and ϕ is the angle in radians.

        - To convert an angle in degrees to an angle in radians,
          use the radians() function, which you just imported.

    + Print out "dist".

"""

# Definition of radius
r = 192500

# Import radians function of math package
from math import radians

# Travel distance of Moon if 12 degrees. Store in dist.
dist = r * radians( 12 )

# Print out dist
print("\nThe distance travelled by the moon over 12 degrees of its orbit is: " + str( dist ) + " Km" )


I am working on the file "Courses/DAT-208x/DAT208x - Week 4 - Section 2 - 2D Numpy Arrays.ipynb".
The first task is:
2D Arithematic
Instructions:

You managed to get hold on the changes in weight, height and age of all baseball players. It is available as a 2D Numpy array, update.

Add np_baseball and update and print out the result.

You want to convert the units of height and weight.

As a first step, create a numpy array with three values: 0.0254, 0.453592 and 1. Name this arary conversion.

Multiply np_baseball with conversion and print out the result.
Can you write Python code for it?

# baseball is available as a regular list of lists
# update is available as 2D Numpy array

# Import numpy package
import numpy as np

# Create np_baseball (3 cols)
np_baseball = np.array(baseball)

# Print out addition of np_baseball and update
# Ans : print( np_baseball + update)

# Create Numpy array: conversion
# Ans: conversion = np.array([0.0254, 0.453592, 1])

# Print out product of np_baseball and conversion
# Ans: print( np_baseball * conversion )


I am working on the file "Courses/DAT-208x/DAT208x - Week 4 - Section 2 - 2D Numpy Arrays.ipynb".
The first task is:
3. Subsetting 2D Numpy Arrays:
Preface:
If your 2D Numpy array has a regular structure, i.e. each row and column has a fixed number of values, complicated ways of subsetting become very easy. Have a look at the code below where the elements "a" and "c" are extracted from a list of lists.
```
    # regular list of lists
    x = [["a", "b"], ["c", "d"]]
    [x[0][0], x[1][0]]
# numpy
import numpy as np
np_x = np.array(x)
np_x[:,0]```

Thus for 2D Numpy arrays:

Indexes before the comma refer to rows.

While those after the comma, refered to as coloumns.

The : is for slicing.

Instructions:

Print out the 50th row of np_baseball.

Make a new variable, np_weight, containing the entire second column of np_baseball.

Select the height (first column) of the 124th baseball player in np_baseball and print it out.
Can you write Python code for it?

# baseball is available as a regular list of lists

# Import numpy package
import numpy as np

# Create np_baseball (2 cols)
np_baseball = np.array(baseball)

# Print out the 50th row of np_baseball
#Ans: print( np_baseball[49,:])

# Select the entire second column of np_baseball: np_weight
#Ans: np_weight = np_baseball[1,:]

# Print out height of 124th player
#Ans: print( np_baseball[] )


I am working on the file "Courses/DAT-208x/DAT208x - Week 4 - Section 2 - 2D Numpy Arrays.ipynb".
The first task is:
Exercise:

RQ1: What charaterizes multi-dimensional Numpy arrays?
Ans: You can create a 2D Numpy array from a regular list of lists.

RQ2: You created the following 2D Numpy array, x:
import numpy as np
    x = np.array(["a", "b", "c", "d"],
                 ["e", "f", "g", "h"] ] )
Which Python command do you use to select the string "g" from x?
Ans: x[1, 2]

RQ3: What does the resulting array z contain after executing the following lines of Python code?
import numpy as np
    x = np.array([[1, 2, 3],
                  [1, 2, 3]])
    y = np.array([[1, 1, 1],
                  [1, 2, 3]])
    z = x - y
Ans: Since the arithematic operations on a two even on a 1D array is done element wise, same goes for ND arrays, i.e. rules are all the same.
import numpy as np
    x = np.array([[1, 2, 3],
                  [1, 2, 3]])
    y = np.array([[1, 1, 1],
                  [1, 2, 3]])
    z = x - y

Lab: 2D Numpy Array

Objective:

Creating 2D arrays.

Perform some analyses on them.

Lab Exercises:

Your First 2D Numpy Arrays.

Baseball data in 2D form.

Subsetting 2D Numpy Arrays.

2D Arithematic

1. Your First 2D Numpy Arrays -- 100xp, status:  earned.

Preface: Before working on the actual MLB data, let's try to create a 2D Numpy array from a small list of lists.
In this exercise, baseball is a list of lists. The main list contains 4 elements. Each of these elements is a list containing the height and the weight of 4 baseball players, in this order.
Instructions:

Use np.array() to create a 2D Numpy array from baseball. Name it np_baseball.

Print out the type of np_baseball.

Print out the shape attribute of np_baseball.

Use np_baseball.shape.
Can you write Python code for it?

# Create baseball, a list of lists
baseball = [[180, 78.4],
            [215, 102.7],
            [210, 98.5],
            [188, 75.2]]

# Import numpy
import numpy as np

# Create a 2D Numpy array from baseball: np_baseball
np_baseball = np.array(baseball)

# Print out the type of np_baseball
print( type( np_baseball ) )

# Print out the shape of np_baseball
print( np_baseball. shape )


I am working on the file "Courses/DAT-208x/DAT208x - Week 4 - Section 2 - 2D Numpy Arrays.ipynb".
The first task is:
Shape of n-dimensional array

We can also look the type of structure our n-dimensional array object is, by calling the shape on the array itself.
< array_name > . shape

shape is a attribute which gives us more information about the structure of the data structure.

Note:

All rules of numpy arrays also apply to multi-dimensional arrays as well.

i.e. an array can only contain a single type.

If we change a (say) float elem to string, all array elements will be coerced to "strings".

i.e. we end up with the homogenous array!

Can think of them as improved list-of-list.
Can you write Python code for it?

# check the shape of the previously created numpy array
np_2d.shape


I am working on the file "Courses/DAT-208x/DAT208x - Week 4 - Section 2 - 2D Numpy Arrays.ipynb".
The first task is:
Subsetting on n-dimensional arrays

As discussed earlier, Numpy n-dimensional arrays share all rules as that of Python array and some of it's own as well.
We can subset them as well, but this time it's a little bit different, here's how:
N-dimensional_array_name[ < row index of desired elem > ] [ < coloumn index of desired elem > ]
Alternative,
N-dimensional_array_name[ < row index> , < col index > ]
Can you write Python code for it?

# subset a row and coloumn

"""
+ Colon before comma specifies both rows.
+ Then follows the usual subsetting of any list.
+ Since we only wan't the 2nd and 3rd coloumn, hence
  we put the indices 1 to 3.

  - Remember, the 3rd index is not computed.

+ The "intersection" gives us two rows and colomns.

"""

print("Two rows and two coloumns: \n" + str(np_2d[:, 1:3]))

# Select a row completely
"""
Here's are n-dimensional array:

col:   0  1  2  3  4  5  6
       ^  ^  ^  ^  ^  ^  ^
   [ [ 1  2  3  4  5  6  7 ]    ----- row 0
     [ 8  9 10 11 12 13 14 ] ]  ----- row 1

i.e we want the whole 1st row 2( index 0 )
"""
print("\nThe 1st row at index 0 is: " + str( np_2d[ 0, :]) )  # second row and coloumns


I am working on the file "Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb".
The first task is:
Accessing Rows:

Syntax: dataframe.loc[ <"row name"> ]

Go to top:TOC
Element access

To get just one element in the table, we can specify both coloumn and row label in the loc().
Syntax:

dataframe.loc[ <"row-name, coloumn name"> ]

dataframe[ <"row-name"> ].loc[ <"coloumn-name"> ]

dataframe.loc[ <"rowName'> ][< "coloumnName" >]

Lab:

Objective:

Practice importing data into python as Pandas DataFrame.

Practise accessig Row and Coloumns

Lab content:

CSV to DataFrame1

CSV to DataFrame2

Square Brackets

Loc1

Loc2

Go to:TOC
CSV to DataFrame1

Preface:
The DataFrame is one of Pandas' most important data structures. It's basically a way to store tabular data, where you can label the rows and the columns.
In the exercises that follow, you will be working wit vehicle data in different countries. Each observation corresponds to a country, and the columns give information about the number of vehicles per capita, whether people drive left or right, and so on. This data is available in a CSV file, named cars.csv. It is available in your current working directory, so the path to the file is simply 'cars.csv'.
To import CSV data into Python as a Pandas DataFrame, you can use read_csv().
Instructions:

To import CSV files, you still need the pandas package: import it as pd.

Use pd.read_csv() to import cars.csv data as a DataFrame. Store this dataframe as cars.

Print out cars. Does everything look OK?
Can you write Python code for it?

"""
# Import pandas as pd
import pandas as pd

# Import the cars.csv data: cars
cars = pd.read_csv("cars.csv")

# Print out cars
print(cars)
"""


I am working on the file "Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb".
The first task is:
CSV to DataFrame2

Preface:
We have a slight of a problem, the row labels are imported as another coloumn, that has no name.
To fix this issue, we are goint to pass an argument index_col = 0 to read_csv(). This is used to specify which coloumn in the CSV file should be used as row label?
Instructions:

Run the code with Submit Answer and assert that the first column should actually be used as row labels.

Specify the index_col argument inside pd.read_csv(): set it to 0, so that the first column is used as row labels.

Has the printout of cars improved now?

Go to top:TOC
Can you write Python code for it?

"""
# Import pandas as pd
import pandas as pd

# Import the cars.csv data: cars
cars = pd.read_csv("cars.csv", index_col=0)

# Print out cars
print(cars)
"""


I am working on the file "Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb".
The first task is:
Loc1

With loc we can do practically any data selection operation on DataFrames you can think of.
loc is label-based, which means that you have to specify rows and coloumns based on their row and coloumn labels.
Instructions:

Use loc to select the observation corresponding to Japan as a Series. The label of this row is JAP. Make sure to print the resulting Series.

Use loc to select the observations for Australia and Egypt as a DataFrame.
Can you write Python code for it?

"""
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out observation for Japan
print( cars.loc['JAP'] )

# Print out observations for Australia and Egypt
print( cars.loc[ ['AUS', 'EG'] ])
"""


I am working on the file "Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb".
The first task is:
Square Brackets

Preface
Selecting coloumns can be done in two way.

variable_containing_CSV_file['coloumn-name']

variable_containing_CSV_file[['coloumn-name']]

The former gives a pandas series, whereas the latter gives a pandas dataframe.
Instructions:

Use single square brackets to print out the country column of cars as a Pandas Series.

Use double square brackets to print out the country column of cars as a Pandas DataFrame. Do this by putting country in two square brackets this time.
Can you write Python code for it?

"""
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out country column as Pandas Series
print( cars['country'])

# Print out country column as Pandas DataFrame
print( cars[['country']])
"""


I am working on the file "Courses/ML in Cybersecurity/Classification/Phishing detection/Phishing detection with ML and feature scaling.ipynb".
The first task is:
Dimensionality reduction with PCA
Can you write Python code for it?

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(X)
X_reduced = pca.transform(X)
print("Reduced dataset shape:", X_reduced.shape)

# PCA only
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='Paired')

print("Meaning of the components:")
for component in pca.components_:
    print(" + ".join("%.3f x %s" % (value, name)
                     for value, name in zip(component, feature_names)))


I am working on the file "Courses/ML in Cybersecurity/Classification/Phishing detection/Phishing detection with ML and feature scaling.ipynb".
The first task is:
Dimensionality reduction with t-SNE
Can you write Python code for it?

from sklearn.manifold import TSNE
X_reduced2 = TSNE(n_components=2).fit_transform(X)
# PCA + t-SNE
X_reduced3 = TSNE(n_components=2).fit_transform(X_reduced)
print("Reduced dataset shape:", X_reduced3.shape)

# t-SNE only
plt.scatter(X_reduced2[:, 0], X_reduced2[:, 1], c=y, cmap='Paired')

# PCA + t-SNE
plt.scatter(X_reduced3[:, 0], X_reduced3[:, 1], c=y, cmap='Paired')


I am working on the file "Courses/ML in Cybersecurity/Classification/Phishing detection/Phishing detection with ML.ipynb".
The first task is:
Clustering: K-means
Can you write Python code for it?

from sklearn.cluster import KMeans
k_means = KMeans(n_clusters=2, random_state=0) # Fixing the RNG in kmeans
k_means.fit(X)
y_pred = k_means.predict(X)

plt.scatter(X_reduced2[:, 0], X_reduced2[:, 1], c=y_pred, cmap='Paired');

TP = 0
TN = 0
FP = 0
FN = 0

for i in range (0, len(y)):
    #print(i, ":", y[i])
    if (y[i] == 1): # Positive
        if (y[i] == y_pred[i]):
            TP+=1
        else:
            FN+=1
    else:
        if (y[i] == y_pred[i]):
            TN+=1
        else:
            FP+=1

print("TP =", TP, "TN =", TN, "FP =", FP, "FN =", FN)

TPR = TP / (TP+FN)
TNR = TN / (TN+FP)
FPR = FP / (FP+TN)
FNR = FN / (TP+FN)
PPV = (TP+TN) / (TP+TN+FP+FN)
NPV = TN / (TN+FN)
Fmeasure = 2*PPV*TPR / (PPV + TPR)

print("TPR =", TPR, "TNR =", TNR, "FPR =", FPR, "FNR =", FNR, "PPV =", PPV, "NPV =", NPV, "F-measure =", Fmeasure)


I am working on the file "Courses/ML in Cybersecurity/Classification/Phishing detection/Phishing detection with ML.ipynb".
The first task is:
Dimensionality reduction with PCA
Can you write Python code for it?


I am working on the file "Courses/ML in Cybersecurity/Classification/Phishing detection/Phishing detection with ML.ipynb".
The first task is:
Dimensionality reduction with t-SNE
Can you write Python code for it?


I am working on the file "Cox Done.ipynb".
The first task is:
If we want to look at covariates, we need a new approach.
We'll use Cox proprtional hazards, a very popular regression model.
To fit in python we use the module lifelines:
http://lifelines.readthedocs.io/en/latest/
Can you write Python code for it?

#Fitting solution
cf = lifelines.CoxPHFitter()
cf.fit(df, 'lifetime', event_col = 'event')
cf.summary


I am working on the file "Cox Done.ipynb".
The first task is:
Model selection
Difficult to do with classic tools (here)
Problem:
1 - Calculate the BMA coefficient values

2 - Try running with different priors
Can you write Python code for it?

#### BMA Coefficient values

#### Different priors


I am working on the file "Cox Done.ipynb".
The first task is:
Problems:
4 - Try adjusting the number of samples for burning and thinnning
5 - Try adjusting the prior and see how it affects the estimate
Can you write Python code for it?

censor = np.array(df["event"].apply(lambda x: 0 if x else 1).tolist())
alpha = pm.Uniform("alpha", 0,50)
beta = pm.Uniform("beta", 0,50)

@pm.observed
def survival(value=df["lifetime"], alpha = alpha, beta = beta ):
    return sum( (1-censor)*(np.log( alpha/beta) + (alpha-1)*np.log(value/beta)) - (value/beta)**(alpha))

mcmc = pm.MCMC([alpha, beta, survival ] )
mcmc.sample(10000, burn = 3000, thin = 20)

pm.Matplot.plot(mcmc)

#Solution to Q5
## Adjusting the priors impacts the overall result
## If we give a looser, less informative prior then we end up with a broader, shorter distribution
## If we give much more informative priors, then we get a tighter, taller distribution

censor = np.array(df["event"].apply(lambda x: 0 if x else 1).tolist())

## Note the narrowing of the prior
alpha = pm.Normal("alpha", 1.7, 10000)
beta = pm.Normal("beta", 18.5, 10000)

####Uncomment this to see the result of looser priors
## Note this ends up pretty much the same as we're already very loose
#alpha = pm.Uniform("alpha", 0, 30)
#beta = pm.Uniform("beta", 0, 30)

@pm.observed
def survival(value=df["lifetime"], alpha = alpha, beta = beta ):
    return sum( (1-censor)*(np.log( alpha/beta) + (alpha-1)*np.log(value/beta)) - (value/beta)**(alpha))

mcmc = pm.MCMC([alpha, beta, survival ] )
mcmc.sample(10000, burn = 5000, thin = 20)
pm.Matplot.plot(mcmc)
#plt.hist([weibull_median(x[0], x[1]) for x in zip(mcmc.trace("alpha"), mcmc.trace("beta"))])


I am working on the file "Cox Done.ipynb".
The first task is:
Problems:
7 - Try testing whether the median is greater than a different values
Can you write Python code for it?

medians = [weibull_median(x[0], x[1]) for x in zip(mcmc.trace("alpha"), mcmc.trace("beta"))]
testing_value = 14.9
number_of_greater_samples = sum([x >= testing_value for x in medians])
100 * (number_of_greater_samples / len(medians))


I am working on the file "Cox Done.ipynb".
The first task is:
The first step in any data analysis is acquiring and munging the data
Our starting data set can be found here:
   http://jakecoltman.com in the pyData post
It is designed to be roughly similar to the output from DCM's path to conversion
Download the file and transform it into something with the columns:
id,lifetime,age,male,event,search,brand
where lifetime is the total time that we observed someone not convert for and event should be 1 if we see a conversion and 0 if we don't.  Note that all values should be converted into ints
It is useful to note that end_date = datetime.datetime(2016, 5, 3, 20, 36, 8, 92165)
Can you write Python code for it?

running_id = 0
output = [[0]]
with open("E:/output.txt") as file_open:
    for row in file_open.read().split("\n"):
        cols = row.split(",")
        if cols[0] == output[-1][0]:
            output[-1].append(cols[1])
            output[-1].append(True)
        else:
            output.append(cols)
    output = output[1:]

for row in output:
    if len(row) == 6:
        row += [datetime(2016, 5, 3, 20, 36, 8, 92165), False]
output = output[1:-1]

def convert_to_days(dt):
    day_diff = dt / np.timedelta64(1, 'D')
    if day_diff == 0:
        return 23.0
    else:
        return day_diff

df = pd.DataFrame(output, columns=["id", "advert_time", "male","age","search","brand","conversion_time","event"])
df["lifetime"] = pd.to_datetime(df["conversion_time"]) - pd.to_datetime(df["advert_time"])
df["lifetime"] = df["lifetime"].apply(convert_to_days)
df["male"] = df["male"].astype(int)
df["search"] = df["search"].astype(int)
df["brand"] = df["brand"].astype(int)
df["age"] = df["age"].astype(int)
df["event"] = df["event"].astype(int)
df = df.drop('advert_time', 1)
df = df.drop('conversion_time', 1)
df = df.set_index("id")
df = df.dropna(thresh=2)
df.median()

###Parametric Bayes
#Shout out to Cam Davidson-Pilon

## Example fully worked model using toy data
## Adapted from http://blog.yhat.com/posts/estimating-user-lifetimes-with-pymc.html
## Note that we've made some corrections

N = 2500

##Generate some random data
lifetime = pm.rweibull( 2, 5, size = N )
birth = pm.runiform(0, 10, N)
censor = ((birth + lifetime) >= 10)
lifetime_ = lifetime.copy()
lifetime_[censor] = 10 - birth[censor]

alpha = pm.Uniform('alpha', 0, 20)
beta = pm.Uniform('beta', 0, 20)

@pm.observed
def survival(value=lifetime_, alpha = alpha, beta = beta ):
    return sum( (1-censor)*(log( alpha/beta) + (alpha-1)*log(value/beta)) - (value/beta)**(alpha))

mcmc = pm.MCMC([alpha, beta, survival ] )
mcmc.sample(50000, 30000)

pm.Matplot.plot(mcmc)
mcmc.trace("alpha")[:]


I am working on the file "Cpp/Cpp14/FileIO/FileIO.ipynb".
The first task is:
Comma separated, ,
has a header
cf.
Viscosity of Polyacrylamide Copolymers by Concentration and Shear Rate
Can you write Python code for it?

copoly_v_DF = pd.read_csv(datafilefolder + "copolymer_viscosity.csv")

copoly_v_DF.describe()

copoly_v_DF.head()


I am working on the file "Cpp/Cpp14/FileIO/FileIO.ipynb".
The first task is:
Then go to CUDA C++14 file binIO_playground.cu or the C++14 version (serial version), binIO_playground.cpp.  Load it with std::ifstream, Input stream class to operate on files.
The most important thing to note is that NumPy reshapes (.reshape) into row-major ordering, i.e.
$$
\lbrace 0,1,\dots mn-1 \rbrace \to \lbrace 0,1, \dots m-1 \rbrace \times \lbrace 0,1, \dots n-1 \rbrace \
k \mapsto (k/n, k \mod{n}) \
$$
and so we'll read in this binary file, with std::ifstream and .read(...) in C++ in row-major ordering assumed for the matrix $A$.
If we want a column-major ordered matrix, we'll have to had loaded the matrix $A$ from the beginning to be column major ordered through .tofile.
std::ifstream
typedef basic_ifstream<char> ifstream;
reinterpret_cast
reinterpret_cast < new_type > ( expression )
Returns a value of type new_type.
std::istream_iterator
Note, cf. https://stackoverflow.com/questions/37588569/using-stdistream-iterator-to-read-binary-data-from-file-stops-prematuraly
"   istream_iterator is an avatar of operator >>; it uses that operator to read from the stream. That is almost never what you want for reading binary data, because >> is a formatted input function. You could probably coerce it to do what you want by using manipulators such as noskipws on the stream, but it would still effectively remain a use of the wrong tool for the job.
If you want an iterator-based access to binary data in a stream, you might be better off using an istreambuf_iterator (which is guaranteed to work character by character) instead."  Angew
std::istreambuf_iterator is a single-pass input iterator that reads successive characters from the std::basic_streambuf object for which it was constructed.
Sample Datasets
http://www.stat.ufl.edu/~winner/datasets.html
.csv to Pandas (Python), .csv to C++
Can you write Python code for it?


I am working on the file "Cpp/Cpp14/FileIO/FileIO.ipynb".
The first task is:
Whitespace separated,  or
no header
cf. Manufacturing Learning Curves
Can you write Python code for it?

Manu_learn = pd.read_csv(datafilefolder+"manuf_learn.dat",header=None,delim_whitespace=True)

Manu_learn


I am working on the file "Cpp/Cpp14/FileIO/FileIO.ipynb".
The first task is:
numpy.fromfile
numpy.fromfile(file, dtype=float, count=-1, sep='')
Can you write Python code for it?

A_in = np.fromfile(datafilefolder+ Afilename, dtype=np.float32)

print(A_in)


I am working on the file "Cpp/Cpp14/FileIO/FileIO.ipynb".
The first task is:
numpy.ndarray.tofile
ndarray.tofile(fid,sep="",format="%s")
Write array to a file as text or binary (default).
Data always written in 'C' order, independent of order of a.
Parameters
fid : file or str
        An open file object, or string containing filename.
sep : str
        Separator between array items for text output.  If "" (empty), a binary file is written, equivalent to file.write(a.tobytes())
format : str
        Format string for text file output.  Each entry in the array is formatted to text by first converting it to closest Python type, and then using "format" % item.
Can you write Python code for it?

m=5
n=4

A = 11.111111*np.array(range(m*n),dtype=np.float32).reshape((m,n))

print(A)

Afilename = "A_mat_5_4.npy"

try:
    A.tofile(datafilefolder+ Afilename )
except IOError:
    if not os.path.exists(datafilefolder):
        os.makedirs(datafilefolder)

print(os.listdir(datafilefolder))
print(os.listdir(os.getcwd()))


I am working on the file "Cpp/Integrate.ipynb".
The first task is:
Below is, mathematically, $f_{-h} := p_1(x)$ with $(x_0,y_0) = (x_0-h, f(x_0-h)), (x_1,y_1) = (x_0,f(x_0))$ and
$\int_{x_0-h}^{x_0} f_{-h}$
Can you write Python code for it?

x_0 = Symbol('x_0',real=True)
f = Function('f')
f_minush = p_1x.subs({xpts[0]:x_0-h,xpts[1]:x_0, ypts[0]:f(x_0-h), ypts[1]:f(x_0) })
integrate( f_minush, (x,x_0-h,x_0 ) )


I am working on the file "Cpp/Integrate.ipynb".
The first task is:
Legendre Polynomials
I don't find the sympy documentation very satisfying (other than listing the argument syntax, no examples of usage, nor further explanation, beyond the barebones argument syntax, is given).  So what I've done here is to try to show what I've done.
Can you write Python code for it?

from sympy.polys.orthopolys import legendre_poly

print "n \t \t \t \t P_n(x) \n"
for i in range(11):
    print str(i) + "\t \t \t \t " , legendre_poly(i,x)

sympy.latex(legendre_poly(2,x))

sympy.N( sympy.integrate(1/(2+x**2),(x,0,3)) )


I am working on the file "Cpp/Integrate.ipynb".
The first task is:
Then, we can use sympy to calculate, symbolically, $f_{h} := p_1(x)$ with $(x_0,y_0) = (x_0, f(x_0)), (x_1,y_1) = (x_0+h,f(x_0+h))$ and
$\int_{x_0}^{x_0+h} f_{h}$
Can you write Python code for it?

f_h = p_1x.subs({xpts[0]:x_0,xpts[1]:x_0+h, ypts[0]:f(x_0), ypts[1]:f(x_0+h) })
integrate( f_h, (x,x_0,x_0+h ) )

( integrate( f_minush, (x,x_0-h,x_0 ) ) + integrate( f_h, (x,x_0,x_0+h ) )  ).simplify()


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Accept (if True)!
Can you write Python code for it?

print( spin_matrix[x,y] )
print( spin_matrix.item(x,y) )

spin_matrix[x,y] *= -1
M += 2*spin_matrix[x,y]
E += deltaE
print(spin_matrix.item(x,y))
print(M)
print(E)

import pygame


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Calculate initial energy
Can you write Python code for it?

# for i in xrange(16): print i  r
# range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.
# xrange is a sequence object that evaluates lazily.

for j in xrange(size):
    for i in xrange(size):
        E -= spin_matrix.item(i,j) * (spin_matrix.item(periodic(i,size,-1),j) + spin_matrix.item(i,periodic(j,size,1)))


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Create and initialize variables
Can you write Python code for it?

E = M = 0
E_av = E2_av = M_av = M2_av = Mabs_av = 0


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
For
2^10 x 2^10 or 1024 x 1024 grid; 50000 trials, temperature T = 1.0, 1.005,...3. (temperature step of 0.005), so 400 different temperatures, 32 x 32 thread block,
Can you write Python code for it?

avgsresults_GPU = np.fromfile("./IsingGPU/data/IsingMetroGPU.bin",dtype=np.float32)

print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

avgsresults_GPU = avgsresults_GPU.reshape( avgsresults_GPU.size/7 ,7) # 7 different averages
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
Evar_avg = avgsresults_GPU[:,2]
M_avg = avgsresults_GPU[:,3]
Mvar_avg = avgsresults_GPU[:,4]
absM_avg = avgsresults_GPU[:,5]
M4_avg = avgsresults_GPU[:,6]

ax.scatter( T, E_avg)
plt.show()

plt.scatter( T, Evar_avg)
plt.show()

plt.scatter( T, M_avg)
plt.show()

plt.scatter(T,Mvar_avg)
plt.show()

plt.scatter(T,absM_avg)
plt.show()

plt.scatter(T,M4_avg)
plt.show()


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
From CLaigit
Can you write Python code for it?

avgsresults_GPU = []

for temp in range(10,31,2):
    avgsresults_GPU.append( np.fromfile("./data/ising2d_CLaigit" + str(temp) + ".bin",dtype=np.float64) )

avgsresults_GPU = np.array( avgsresults_GPU)
print( avgsresults_GPU.shape, avgsresults_GPU.size)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
M_avg = avgsresults_GPU[:,2]
heat_cap_avg = avgsresults_GPU[:,3]
mag_sus_avg = avgsresults_GPU[:,4]

ax.scatter( T, E_avg)
plt.show()

plt.scatter( T, M_avg)
plt.show()

plt.scatter( T, heat_cap_avg)
plt.show()

plt.scatter( T, mag_sus_avg)
plt.show()


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
From drafts
Can you write Python code for it?

avgsresults_GPU = np.fromfile("./IsingGPU/drafts/data/IsingMetroGPU.bin",dtype=np.float32)

print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

avgsresults_GPU = avgsresults_GPU.reshape( avgsresults_GPU.size/7 ,7) # 7 different averages
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
Evar_avg = avgsresults_GPU[:,2]
M_avg = avgsresults_GPU[:,3]
Mvar_avg = avgsresults_GPU[:,4]
absM_avg = avgsresults_GPU[:,5]
M4_avg = avgsresults_GPU[:,6]

ax.scatter( T, E_avg)
plt.show()

avgsresults_GPU = np.fromfile("./IsingGPU/drafts/IsingGPU/data/IsingMetroGPU_runs10.bin",dtype=np.float32)

print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)
avgsresults_GPU = avgsresults_GPU.reshape( avgsresults_GPU.size/7 ,7) # 7 different averages
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
Evar_avg = avgsresults_GPU[:,2]
M_avg = avgsresults_GPU[:,3]
Mvar_avg = avgsresults_GPU[:,4]
absM_avg = avgsresults_GPU[:,5]
M4_avg = avgsresults_GPU[:,6]

ax.scatter( T, E_avg)
plt.show()

plt.scatter( T, Evar_avg)
plt.show()

plt.scatter( T, M_avg)
plt.show()

plt.scatter(T,Mvar_avg)
plt.show()

plt.scatter(T,absM_avg)
plt.show()

plt.scatter(T,M4_avg)
plt.show()

avgsresults_GPU = np.fromfile("./IsingGPU/drafts/IsingGPU/data/IsingMetroGPU.bin",dtype=np.float32)
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)
avgsresults_GPU = avgsresults_GPU.reshape( avgsresults_GPU.size/7 ,7) # 7 different averages
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
Evar_avg = avgsresults_GPU[:,2]
M_avg = avgsresults_GPU[:,3]
Mvar_avg = avgsresults_GPU[:,4]
absM_avg = avgsresults_GPU[:,5]
M4_avg = avgsresults_GPU[:,6]

ax.scatter( T, E_avg)
plt.show()

plt.scatter( T, Evar_avg)
plt.show()

plt.scatter( T,...


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Initialize (all spins up), explicitly shown
Can you write Python code for it?

Lx=256; Ly=256
spin_matrix = np.zeros((Lx,Ly),np.int8)

print(spin_matrix.shape)
spin_matrix.fill(1)
spin_matrix

def initialize_allup( spin_matrix, J=1.0 ):
    Lx,Ly = spin_matrix.shape

    spin_matrix.fill(1)
    M = spin_matrix.sum()
    # Calculate initial energy
    E=0
    for j in xrange(Ly):
        for i in xrange(Lx):
            E += (-J)*spin_matrix.item(i,j) * \
                (spin_matrix.item(periodic(i,Lx,+1),j) + spin_matrix.item(i,periodic(j,Ly,1)) )
    print "M: ",M," E: ", E
    return E,M

E,M = initialize_allup( spin_matrix)

def initialize_allup1( spin_matrix, J=1.0 ):
    Lx,Ly = spin_matrix.shape

    spin_matrix.fill(1)
    M = spin_matrix.sum()
    # Calculate initial energy
    E=0
    for j in xrange(Ly):
        for i in xrange(Lx):
            E -= J*spin_matrix.item(i,j) * \
                (spin_matrix.item(periodic(i,Lx,-1),j) + spin_matrix.item(i,periodic(j,Ly,1)) )
    print "M: ",M," E: ", E
    return E,M

E,M = initialize_allup( spin_matrix)

Lx=512; Ly=512
spin_matrix = np.zeros((Lx,Ly),np.int8)

E,M = initialize_allup1( spin_matrix)
E,M = initialize_allup( spin_matrix)

Lx=1024; Ly=1024
print(Lx*Ly)
spin_matrix = np.zeros((Lx,Ly),np.int8)

E,M = initialize_allup1( spin_matrix)
E,M = initialize_allup( spin_matrix)

math.pow(2,31)


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Metropolis MonteCarlo computation, 1 single step or iteration, done explicitly:
Can you write Python code for it?

x = int(np.random.random()*size)
print(x)
y = int(np.random.random()*size)
print(y)

deltaE = 2*spin_matrix.item(i,j) * \
          (spin_matrix.item(periodic(x,size,-1),y) + spin_matrix.item(periodic(x,size,1),y) + \
          spin_matrix.item(x,periodic(y,size,-1))+spin_matrix.item(x,periodic(y,size,1)))
print(deltaE)

print( w[deltaE + 8] )

np.random.random()

print( np.random.random() <= w[deltaE+8])


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Reading out data from ./IsingGPU/FileIO/output.h
Data is generated by the parallel Metropolis algorithm in CUDA C++ in the subdirectory ./IsingGPU/data/, which is done by the function process_avgs in ./IsingGPU/FileIO/output.h.  The values are saved as a character array, which then can be read in as a NumPy array of float32's.  Be sure to enforce, declare the dtype to be float32.
Can you write Python code for it?

avgsresults_GPU = np.fromfile("./IsingGPU/data/IsingMetroGPU.bin",dtype=np.float32)

print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

avgsresults_GPU = avgsresults_GPU.reshape(201,7) # 7 different averages
print(avgsresults_GPU.shape)
print(avgsresults_GPU.size)

avgsresults_GPU

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
T = avgsresults_GPU[:,0]
E_avg = avgsresults_GPU[:,1]
ax.scatter( T, E_avg)
plt.show()

Evar_avg = avgsresults_GPU[:,2]
plt.scatter( T, Evar_avg)
plt.show()

M_avg = avgsresults_GPU[:,3]
Mvar_avg = avgsresults_GPU[:,4]
absM_avg = avgsresults_GPU[:,5]
M4_avg = avgsresults_GPU[:,6]
#fig = plt.figure()
#ax = fig.add_subplot(4,1,1)
plt.scatter( T, M_avg)
#fig.add_subplot(4,1,2)
#plt.scatter(T,Mvar_avg)
#fig.add_subplot(4,1,3)
#plt.scatter(T,absM_avg)
#fig.add_subplot(4,1,4)
#plt.scatter(T,M4_avg)
plt.show()

plt.scatter(T,Mvar_avg)
plt.show()

plt.scatter(T,absM_avg)
plt.show()

plt.scatter(T,M4_avg)
plt.show()


I am working on the file "Cpp/Ising/ising.ipynb".
The first task is:
Setup array for possible energy changes
Can you write Python code for it?

w = np.zeros(17, np.float64)
for de in xrange(-8,9,4):
    print de
    w[de+8] = math.exp(-de/temp)

print w


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
(Quick quiz: why did the snippet print "Go to work" here? What is the variable "day" set to?)
Let's take the snippet apart to see what happened. First, note the statement
Can you write Python code for it?


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
1.11 Plotting with Matplotlib
We can generally understand trends in data by using a plotting program to chart it. Python has a wonderful plotting library called Matplotlib. The Jupyter notebook interface we are using for these notes has that functionality built in.
First off, it is important to import the library. We did this at the very beginning of this whole jupyter notebook, but here it is in case you've jumped straight here without running the first code line:
Can you write Python code for it?

import matplotlib.pyplot as plt
%matplotlib inline


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
1.7 Code Example: The Fibonacci Sequence
The Fibonacci sequence is a sequence in math that starts with 0 and 1, and then each successive entry is the sum of the previous two. Thus, the sequence goes 0,1,1,2,3,5,8,13,21,34,55,89,...
A very common exercise in programming books is to compute the Fibonacci sequence up to some number n. First I'll show the code, then I'll discuss what it is doing.
Can you write Python code for it?

n = 10
sequence = [0,1]
for i in range(2,n): # This is going to be a problem if we ever set n <= 2!
    sequence.append(sequence[i-1]+sequence[i-2])
print (sequence)


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
2.3 Matrix operations
Matrix objects act sensibly when multiplied by scalars:
Can you write Python code for it?


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
3.5 List Comprehensions and Generators
List comprehensions are a streamlined way to make lists. They look something like a list definition, with some logic thrown in. For example:
Can you write Python code for it?

evens1 = [2*i for i in range(10)]
print(evens1)


I am working on the file "Crash Course v0.62.ipynb".
The first task is:
3.6 Factory Functions
A factory function is a function that returns a function. They have the fancy name lexical closure, which makes you sound really intelligent in front of your CS friends. But, despite the arcane names, factory functions can play a very practical role.
Suppose you want the Gaussian function centered at 0.5, with height 99 and width 1.0. You could write a general function.
Can you write Python code for it?

def gauss(x,A,a,x0):
    return A*np.exp(-a*(x-x0)**2)