1 of 44

NumPy, Indexing, Materials-Based Research

1

Data 6 Summer 2022

LECTURE 05

What it means to work with data.

Developed by students and faculty at UC Berkeley and Tuskegee University

data6.org/su22/syllabus/#acknowledgements-

2 of 44

Icebreaker & Check-In

2

3 of 44

Week 2

Announcements!

  • Homework 1 has been released and will be due on 7/15 @ 11 PM
    • Note the deadline extension
    • If you’re having issues accessing the assignment, post on Ed or come to Office Hours
  • Office Hours take place on Tuesdays and Thursdays 1-3 PM in Evans 6
  • Post on Ed if you have questions about particular concepts or assignment questions

3

4 of 44

Today’s Roadmap

Lecture 05, Data 6 Summer 2022

  1. Array Functions
  2. NumPy
  3. Indexing
  4. Materials-Based Research

4

5 of 44

Warmup

Suppose we have two arrays containing the resident populations of several states in 2020 and 2021. Assume each array contains information about the same states in the same order.

How would you compute the percentage change in state populations from 2020 to 2021?

5

2019 pop

(in millions)

2020 pop

(in millions)

.Alabama

5.025

5.040

.Alaska

0.732

0.733

.Arizona

7.178

7.276

.Arkansas

3.012

3.026

.California

39.500

39.238

pop_2020 = make_array(5.025, .732, 7.178, 3.012, 39.500)

pop_2021 = make_array(5.040, .733, 7.276, 3.026, 39.238)

In [ ]:

...

In [ ]:

6 of 44

Warmup

Suppose we have two arrays containing the resident populations of several states in 2020 and 2021. Assume each array contains information about the same states in the same order.

How would you compute the percentage change in state populations from 2020 to 2021?

6

pop_2020 = make_array(5.025, .732, 7.178, 3.012, 39.500)

pop_2021 = make_array(5.040, .733, 7.276, 3.026, 39.238)

In [ ]:

...

In [ ]:

100 * (pop_2021 - pop_2020) / pop_2020

In [3]:

array([ 0.29850746, 0.13661202, 1.36528281, 0.46480744, -0.66329114])

Out [3]:

(final - initial) / initial

2019 pop

(in millions)

2020 pop

(in millions)

.Alabama

5.025

5.040

.Alaska

0.732

0.733

.Arizona

7.178

7.276

.Arkansas

3.012

3.026

.California

39.500

39.238

7 of 44

Array Functions

7

1. Array Functions

2. NumPy

3. Indexing

4. Materials-Based Research

8 of 44

Standard Functions

8

Call expression format

Example(s)

len(arr)

len(str_arr) # 5�len(empty_arr) # 0

max(arr)

min(int_arr) # -4

min(arr)

max(str_arr) # 'yd'

sum(arr)

sum(int_arr) # 6

sum(str_arr) # TypeError

Compare

9 of 44

Standard Functions

9

Call expression format

Example(s)

len(arr)

len(str_arr) # 5len(empty_arr) # 0

max(arr)

min(int_arr) # -4

min(arr)

max(str_arr) # 'yd'

sum(arr)

sum(int_arr) # 6

sum(str_arr) # TypeError

While the function names are identical to what we saw for int/float/strs, the call expressions evaluate differently with our new array data type.

Compare

10 of 44

Quick Check 1

Recall the definition of an average:

The average, or mean, of a collection of numbers is the sum of all the elements of the collection, divided by the number of elements in the collection.

How would you compute the average of an array arr?

10

arr = make_array(30, -40, -4.5, 0, 35)

avg = ...

avg

In [ ]:

Quick Check

11 of 44

NumPy

11

1. Array Functions

2. NumPy

3. Indexing

4. Materials-Based Research

12 of 44

NumPy: A Convenient Function Library

Earlier, we computed averages using built-in Python functions:

Computing averages of array elements happens a lot in data science!

The NumPy package function np.average() is human-readable and convenient.

12

arr = make_array(30, -40, -4.5, 0, 35)

avg = sum(arr)/len(arr)

avg

In [2]:

4.1

Out [2]:

arr = make_array(30, -40, -4.5, 0, 35)

avg = np.average(arr)

avg

In [2]:

4.1

Out [2]:

13 of 44

The NumPy package

NumPy (pronounced “num pie”) is �a Python package* with convenient and�powerful functions for manipulating arrays.

13

*For our purposes, “library”, “package”, and “module” all mean similar things.

arr = make_array(30, -40, -4.5, 0, 35)

avg = np.average(arr)

avg

In [2]:

4.1

Out [2]:

import numpy as np

In [1]:

import numpy as np

Anytime we want to use NumPy, we run

We generally put this import statement at the top of our notebook,�then prepend np. to call a NumPy function.

14 of 44

Element-wise NumPy Functions

We’ll point you to NumPy functions as they come up; you don’t need to memorize them. The course website has a list of some of them.

14

NumPy functions

Many of these functions work on both arrays and individual numbers.

N-length array

N-length array

Demo

15 of 44

Common NumPy Functions

15

NumPy function

Return value

np.average(arr)

np.mean(arr)

The average (i.e., mean) value of arr

np.sum(arr)

The sum of all elements in arr

np.prod(arr)

The product of all elements in arr

np.count_nonzero(arr)

The number of elements in arr that are not equal to 0

NumPy functions

N-length array

N-length array

Demo

16 of 44

Even More Functions

16

NumPy function

Return value

np.average(arr)

np.mean(arr)

The average (i.e., mean) value of arr

np.sum(arr)

The sum of all elements in arr

np.prod(arr)

The product of all elements in arr

np.count_nonzero(arr)

The number of elements in arr that are not equal to 0

NumPy functions

N-length array

N-length array

Demo

17 of 44

Questions About Functions?

17

Data 6 Python Reference™

18 of 44

Side Note: The datascience Package

datascience package import statement:

  • The slightly different syntax allows us to call package functions without prepending datascience.
  • The make_array() function�is from this package!

18

Fun fact: The datascience package was written �by UC Berkeley specifically for data science education. It’s designed to support many Python packages like NumPy.

“Import everything”

19 of 44

Indexing

19

1. Array Functions

2. NumPy

3. Indexing

4. Materials-Based Research

20 of 44

Array Methods

Methods are functions that we call with “dot” syntax. There are several array methods that make it easy to calculate values of interest.

Terminology note: Method calls are where the function operates directly on the array arr.

In these examples, method calls are equivalent to the NumPy package functions.

20

The most common array method is item(), which is used for array indexing.

21 of 44

An Element’s Index Is Its Position in an Array

When people stand in a line, each person has a position.

Similarly, each element (i.e., value) of an array has a position – called its index.

Python, like most programming languages, is 0-indexed. This means that in an array, the first element has index 0, not 1.

21

Person 1

Person 7

Index 0

Index 6

Indices

0 1 2 3 4

For a length-5 array:

22 of 44

Array Indexing

We can access an element in an array by using its index and the item() method:

arr.item(index)

22

Though int_arr has 5 elements, the largest valid index is 4.

Demo

23 of 44

Negative Indexing

We can also “count backwards” using negative indexes.

  • -1 corresponds to the last element in a list.
  • -2 corresponds to the second last element in a list.
  • And so on...

23

Demo

24 of 44

Questions?

24

25 of 44

Quick Check 2

What is the value of five after running this code?

25

Quick Check

26 of 44

Research Using

Existing Data

26

1. Array Functions

2. NumPy

3. Indexing

4. Materials-Based Research

27 of 44

Gathering Data for Research and Analysis

All data are created/generated from human input:

  • Definition of variables
  • Research design and measurement

However, the researcher and data scientist are often not the same person.�Data scientists therefore need to consider the context of how researchers generated data from existing materials.

27

Conduct surveys, experiments, interviews, ethnography,�measurements…

Data

Conceptualize variables and define domains

Pose research question

+

+

Data Scientist

Researcher

28 of 44

Gathering Data for Research and Analysis

Validity A quality of a measure concerning how accurate it is.

  • Internal Validity: How accurately are we measuring the defined concepts?
  • External Validity:
    • How representative is the group being studied?
    • How “real” is this study?

Generalizability The extent to which results or conclusions based on one population can be applied to others.

28

A researcher considers both validity and generalizability throughout the data gathering process.

Conduct surveys, experiments, interviews, ethnography,�measurements…

Data

Conceptualize variables and define domains

Pose research question

+

+

Data Scientist

Researcher

29 of 44

Using Existing Data from a Different Context

Validity A quality of a measure concerning how accurate it is.

  • Internal Validity: How accurately are we measuring the defined concepts?
  • External Validity:
    • How representative is the group being studied?
    • How “real” is this study?

Generalizability The extent to which results or conclusions based on one population can be applied to others.

29

If we did not create the original dataset, we will need to separately consider whether the data are valid and generalizable for our own research question.

Conduct surveys, experiments, interviews, ethnography,�measurements…

Data

Conceptualize variables and define domains

Pose research question

+

+

Data Scientist

Researcher

30 of 44

Using Existing Data

Pros

  • Inexpensive – the data are there; you just have to gain access to them
  • Data can be reused and combined with other data
  • Effective for social description of large and heterogeneous populations
  • Can study phenomena that unfold over extended periods of time.
  • The data are often nonreactive (i.e. the subjects will not be disrupted by the study)

30

31 of 44

Using Existing Data

Cons

  • Can only study measurable phenomena (for which variables were recorded)
  • Threat to internal validity: No control over creation process from concept to variable
  • Threat to external validity: Potential bias in what is available.
  • Which groups were studied
  • Selective deposit/survival: what was archived
  • No control over quality of data

31

32 of 44

Units of Analysis

32

1. Array Functions

2. NumPy

3. Indexing

4. Materials-Based Research

33 of 44

Units of Analysis

The types of entities we are analyzing:

  • Individuals
  • Groups (families, classes, gangs, ...) �
  • Localities (cities, counties, countries, …) �
  • Organizations, industries, political units, social artifacts, etc.

33

34 of 44

Units of Analysis

The types of entities we are analyzing:

  • Individuals
  • Groups (families, classes, gangs, ...) �
  • Localities (cities, counties, countries, …) �
  • Organizations, industries, political units, social artifacts, etc.

Income

individual�income��household income��average income

Race/Ethnicity

# People

individual�race/ethnicity��–���population demographics

–���# members���population size

34

The concept of unit of analysis is directly linked to the concept of “variables”.�Variables describe the unit of analysis.

35 of 44

UC Berkeley and Simpson’s Paradox

Graduate School Admissions at UC Berkeley, Fall 1973.

35

However, when disaggregated (or disentangled) by department,�Women had small but significantly higher admission rates in many departments.

All

Men

Women

Applicants

Admitted

Applicants

Admitted

Applicants

Admitted

Total

12,763

41%

8,442

44%

4,321

35%

Dept

All

Men

Women

Applicants

Admitted

Applicants

Admitted

Applicants

Admitted

A

933

64%

825

62%

108

82%

B

585

63%

560

63%

25

68%

C

918

35%

325

37%

593

34%

D

792

34%

417

33%

375

35%

E

584

25%

191

28%

393

24%

F

714

6%

373

6%

341

7%

Total

4526

39%

2691

45%

1835

30%

Men are significantly more likely than women to be admitted to UC Berkeley graduate school.

Greater percentage of successful applicants�than other gender

Greater number of applicants than other gender

(note: UC changed gender counting policy to include non-binary as of 2016)

(and men to less competitive depts with higher rates of admission).

Furthermore, women tended to apply to more competitive depts with lower rates of admission

36 of 44

Back to the ACS

36

Household survey

Private dataset by household

Public dataset by geographic region

aggregation

Table 1

Table 2

(last lecture)

37 of 44

Individual Level (Private Dataset)

37

38 of 44

ACS: What Is Released to the Public

38

Household survey

Private dataset by household

Public dataset by geographic region

aggregation

Table 1

Table 2

(this lecture)

39 of 44

ACS’s Public Units of Analysis

39

The ACS only provides an aggregated view of data by region and specific disaggregations by income and sex.

Researchers will therefore find it difficult (if not impossible) to disentangle the impact of certain variables, e.g. by race/ethnicity.

Table 2

Public dataset by geographic region

Table 2

40 of 44

Questions?

40

41 of 44

In Conclusion…

41

42 of 44

Summary

  • Array functions allow us to operate on and aggregate data in arrays
  • While some functions are built-in to Python, others come from the NumPy library, which contains many useful array methods
  • To retrieve a specific element/item in an array, you use the element’s index
    • Remember that indices start at 0, not 1
  • Sometime, we (data scientists) can work with existing data gathered by researchers
    • But oftentimes, that data is limited in its validity and generalizability
    • It is also important to understand the multiple units of analysis that we can use to answer questions, ranging from the individual level to the population level

42

43 of 44

Recap

Next Time

  • Array Functions
  • NumPy
  • Indexing
  • Materials-Based Research
  • Overview of BRFSS Data
  • Tables!
  • Columns and Variables
  • Table Methods

43

44 of 44

Week 1

Announcements!

  • Office hours start today
    • Tuesdays and Thursdays 1-3 PM in Evans 6
  • Homework 1 will be released today and due on 7/14 @ 11PM

44