0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Automating GIS Processes 2024 写経 Exercise 1(Hints、Problem 1途中まで)

Last updated at Posted at 2025-05-06

前回の続きです。

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)

image.png

関数の入力が受け入れられるものかどうかを確認するために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)として実行する。
image.png

Apply()ing an anonymous lambda function

上記の続き。単純な関数ならば、lambda関数にしてもよいでしょう。

(愚痴)lambda関数は単純な演算や処理だけにしてほしいです。三項演算子やif文が入っているlambda関数は可読性に難があると思います。

Iterating over multiple lists simultaneously

zipを使うと、複数のリストの同時ループができまず。これは便利!!

image.png

ただし、リストの中身の数が違うときは、最短のリストでループが回ります。気を付けましょう。
image.png

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)

image.png

中途半端ですが、今回はここまでとします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?