You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
4. Arrays are fast but inflexible - the entire array must be of a single type.
@@ -1151,18 +1155,7 @@ print(y)
1151
1155
print(np.dot(x, y))
1152
1156
```
1153
1157
1154
-
3. You can rearrange the same array into different configurations
1155
-
1156
-
``` python
1157
-
# Use method chaining to link actions together
1158
-
x1 = x.reshape(3,3)
1159
-
x2 = x.reshape(9,1)
1160
-
1161
-
print(x1)
1162
-
print(x2)
1163
-
```
1164
-
1165
-
4. (Optional) Matlab gotcha: 1-D arrays have no transpose
1158
+
3. (Optional) Matlab gotcha: 1-D arrays have no transpose
1166
1159
1167
1160
``` python
1168
1161
print(x)
@@ -1398,7 +1391,7 @@ This is most common way to get data
1398
1391
3. If you want specific rows or columns, pass in a list
1399
1392
1400
1393
``` python
1401
-
data.loc[['Italy','Poland'], :]
1394
+
data.loc[['Italy','Poland'], ["1952","1962"]]
1402
1395
```
1403
1396
1404
1397
4. (Optional) `.iloc` follows list index conventions ("up to, but not including)", but `.loc` does the intuitive right thing ("A through B")
@@ -1451,6 +1444,25 @@ This is most common way to get data
1451
1444
print(subset.max(axis=None))
1452
1445
```
1453
1446
1447
+
\*\*\*( Optional) Get x/y labels for the cell that matches a criterion
1448
+
1449
+
``` python
1450
+
# Which values match the criterion?
1451
+
subset == subset.max().max()
1452
+
1453
+
# Return value at position, code all other cells as NA
1454
+
val = subset[subset ==subset.max().max()]
1455
+
1456
+
# Drop rows where all values are NA, then drop columns where values are NA
1457
+
val.dropna(how="all").dropna(axis=1)
1458
+
1459
+
# Putting it all together: Get index label and column label for last remaining cell
1460
+
names = val.dropna(how="all").dropna(axis=1)
1461
+
1462
+
print(names.index[0])
1463
+
print(names.columns[0])
1464
+
```
1465
+
1454
1466
### (Optional) Filter on label properties
1455
1467
1456
1468
1. `.filter()` always returns the same type as the original item, whereas `.loc` and `.iloc` might return a data frame or a series.
@@ -1738,7 +1750,37 @@ print(df3.shape)
1738
1750
print(df_join.head())
1739
1751
```
1740
1752
1741
-
3. The resulting table loses its index because `surveys.record_id` is not being used in the join. To keep `record_id` as the index for the final table, we need to retain it as an explicit column.
1753
+
3. Use the additional information in the joined data set to inform your analyses:
5. (Optional) The resulting table loses its index because `surveys.record_id` is not being used in the join. To keep `record_id` as the index for the final table, we need to retain it as an explicit column.
1742
1784
1743
1785
``` python
1744
1786
# Don't set record_id as index during initial import
@@ -1748,7 +1790,7 @@ print(df3.shape)
1748
1790
df_join.head()
1749
1791
```
1750
1792
1751
-
4. Aside: Method chaining formatting options
1793
+
6. Aside: Method chaining formatting options
1752
1794
1753
1795
``` python
1754
1796
# Python allows free line breaks inside parens
@@ -1770,7 +1812,7 @@ print(df3.shape)
1770
1812
.set_index("record_id")
1771
1813
```
1772
1814
1773
-
5. Get the subset of species that match a criterion, and join on that subset. The "inner" join only includes rows where both tables match on the key column; it's a strategy for filtering the first table by the second table.
1815
+
7. Get the subset of species that match a criterion, and join on that subset. The "inner" join only includes rows where both tables match on the key column; it's a strategy for filtering the first table by the second table.
1774
1816
1775
1817
``` python
1776
1818
# Get the taxa column, masking the rows based on which values match "Bird"
3. Use string methods for filtering. This works for `str` but not `obj`; if text data has been imported as `obj`, re-cast it to `str`.
1831
1873
1832
1874
``` python
1833
1875
# Which species are in the taxa "Bird"?
@@ -2270,18 +2312,13 @@ Python steps through the branches of the conditional in order, testing each in t
2270
2312
Often, you want some combination of things to be true. You can combine relations within a conditional using `and` and `or`.
2271
2313
2272
2314
``` python
2273
-
mass = [1, 2, 3, 4, 5]
2274
-
velocity = [5, 4, 3, 2, 5]
2315
+
mass = [1, 2, 3, 4]
2316
+
velocity = [4, 3, 2, 1]
2275
2317
2276
2318
form, vin zip(mass, velocity):
2277
-
if m <= 3 and v <= 3:
2278
-
print("Small and slow")
2279
-
elif m <= 3 and v > 3:
2280
-
print("Small and fast")
2281
-
elif m > 3 and v <= 3:
2282
-
print("Large and slow")
2283
-
else:
2284
-
print("Check data")
2319
+
print(m, v)
2320
+
if m < 2 or v > 2:
2321
+
print("At least one of our critera is true")
2285
2322
```
2286
2323
2287
2324
- Use () to group subsets of conditions
@@ -2333,41 +2370,63 @@ print_greeting()
2333
2370
1. Positional arguments
2334
2371
2335
2372
``` python
2336
-
def print_date(year, month, day):
2373
+
def format_date(year, month, day):
2337
2374
"""Print the formatted date. This works with strings or integers."""
2338
2375
2339
2376
formatted_date = f"{year}/{month}/{day}"
2340
2377
print(formatted_date)
2341
2378
2342
-
print_date(1871, 3, 19)
2379
+
format_date(1871, 3, 19)
2343
2380
```
2344
2381
2345
2382
2. (Optional) Keyword arguments
2346
2383
2347
2384
``` python
2348
-
print_date(month=3, day=19, year=1871)
2385
+
format_date(month=3, day=19, year=1871)
2349
2386
```
2350
2387
2351
2388
### Functions may return a result to their caller using `return`
2352
2389
2353
2390
1. Use `return ...` to give a value back to the caller. `return` ends the function's execution and *returns* you to the code that originally called the function.
2354
2391
2392
+
``` python
2393
+
def format_date(year, month, day):
2394
+
"""Print the formatted date. This works with strings or integers."""
2395
+
2396
+
formatted_date = f"{year}/{month}/{day}"
2397
+
return formatted_date
2398
+
2399
+
d = format_date(1871, 3, 19)
2400
+
print(d)
2401
+
```
2402
+
2403
+
2. You should explicitly handle common problems. Start with a simple base function.
2404
+
2355
2405
``` python
2356
2406
def average(values):
2357
2407
"""Return average of values."""
2358
2408
2359
2409
return sum(values) / len(values)
2360
2410
```
2361
2411
2412
+
3. Test your function on inputs that should work.
2413
+
2362
2414
``` python
2363
-
a = average([1, 3, 4])
2415
+
a = average([1, 2, 3, 4])
2364
2416
print(a)
2365
2417
```
2366
2418
2367
-
2. You should explicitly handle common problems:
2419
+
4. Test against edge cases and erroneous input.
2420
+
2421
+
``` python
2422
+
test1 = []
2423
+
test2 = ["a", "b", "c", "d"]
2424
+
```
2425
+
2426
+
5. Revise based on test results.
2368
2427
2369
2428
``` python
2370
-
print(average([]))
2429
+
av1 = average(test1)
2371
2430
```
2372
2431
2373
2432
``` python
@@ -2380,7 +2439,25 @@ print_greeting()
2380
2439
return sum(values) / len(values)
2381
2440
```
2382
2441
2383
-
3. Notes:
2442
+
6. You can choose to handle errors within the function, or by validating input ahead of time. Either choice is defensible, just be consistent.
2443
+
2444
+
``` python
2445
+
av2 = average(test2)
2446
+
```
2447
+
2448
+
``` python
2449
+
def average(values):
2450
+
"""Return average of values, or None if no values are supplied."""
2451
+
2452
+
if len(values) == 0:
2453
+
return None
2454
+
elif all([type(x) == int for x in values]):
2455
+
return sum(values) / len(values)
2456
+
else:
2457
+
return None
2458
+
```
2459
+
2460
+
7. Notes:
2384
2461
2385
2462
1. `return` can occur anywhere in the function, but functions are easier to understand if return occurs:
0 commit comments