前回の続きです。
Hints
assert statements
assert statements are often used in functions to ensure the input values are acceptable. Consider the following example:
def divide(dividend, divisor):
"""Return the division of dividend by divisor."""
assert divisor != 0, "Cannot divide by zero."
return (dividend / divisor)
関数の入力が受け入れられるものかどうかを確認するためにassert
を使いましょう。
うーん、いやー、これはちょっと検討の余地ありかと。
たとえば、ruffの assert (S101)に引っかかります。
学習用のコードならばありですが、プロダクションコードでは、面倒でもraise
するほうが良いと思います。
Alternatives to pandas.DataFrame.iterrows()
Pandas’ apply() method
iterrows()
を使ってpandas.DataFrame
をループ処理することができますが、処理速度を考慮し、apply
を使いましょう。
これはよく聞く話ですね。
pandas.DataFrameのループ速度比較(iterrows vs apply)
事前に引数で受け取った行の列を使った処理を関数として定義にしておき、apply(function, axis=1)
として実行する。
Apply()ing an anonymous lambda function
上記の続き。単純な関数ならば、lambda関数にしてもよいでしょう。
(愚痴)lambda関数は単純な演算や処理だけにしてほしいです。三項演算子やif文が入っているlambda関数は可読性に難があると思います。
Iterating over multiple lists simultaneously
zip
を使うと、複数のリストの同時ループができまず。これは便利!!
ただし、リストの中身の数が違うときは、最短のリストでループが回ります。気を付けましょう。
exercise-1
なんと、ここまでは前座です。ここからが本番です。
exercise-1
Exercise 1: Working with Geometric Objects
This week we will practice how to create geometric objects using shapely in Python.
In this exercise, you will also need to apply your skills from the Geo-Python course. In the first set of problems (1-2) you will define your own functions for handling geometric objects. In the second set of problems (3-4), you will read in data from a file using pandas and create geometries based on coordinate information in the input data.
最初の問題セット(1~2)では、幾何学オブジェクトを扱うための独自の関数を定義します。2番目の問題セット(3~4)では、pandasを使ってファイルからデータを読み込み、入力データの座標情報に基づいてジオメトリを作成します。
(1a)
Create a function called create_point_geometry() that accepts two parameters, x_coord and y_coord. The function should return a shapely.geometry.Point geometry object.
x_coordとy_coordの2つのパラメータを受け取るcreate_point_geometry()という関数を作成します。この関数はshapely.geometry.Pointジオメトリオブジェクトを返します。
こんな感じですね。
from shapely.geometry import Point
def create_point_geometry (x_coord, y_coord):
point = Point(x_coord, y_coord)
return point
Test your function by running the following code cell:
作った関数をテストします。
point1 = create_point_geometry(0.0, 1.1)
print(point1)
print(point1.geom_type)
中途半端ですが、今回はここまでとします。