LoginSignup
0
0

Command R+ に次の問を出しました。

Julia で、PostgreSQL のテーブルを Dataframe に読み込む方法

続けて次の依頼をしました。

サンプルのプログラムを示して下さい。

結果を修正したプログラム

commandr.jl
#! /snap/bin/julia

# using Pkg
# Pkg.add("LibPQ")
# Pkg.add("DataFrames")

using LibPQ
using DataFrames

# データベースへの接続情報
db_url = "postgresql://scott:tiger123@localhost/city"

# データベースに接続
conn = LibPQ.Connection(db_url)

# テーブル名を指定
table_name = "cities"

# テーブルを Dataframe に読み込む
df = DataFrame(execute(conn, "SELECT * FROM $table_name"))

# Dataframe の先頭 6 行を表示
println("先頭 6 行のデータ:")
println(first(df, 6))
println()

# Dataframe の列名を表示
println("列名:")
println(names(df))
println()

# Dataframe の行数と列数を表示
println("データのサイズ: $(size(df))")
println()

#
num_high_population = count(row -> row[:population] >= 50000, eachrow(df))
println("人口が 50000 以上の都市の数: $num_high_population")
println()

# データベースとの接続を閉じる
close(conn)

実行結果

$ ./commandr.jl 
先頭 6 行のデータ:
6×4 DataFrame
 Row │ id       name     population  date_mod   
     │ String?  String?  Int32?      Date       
─────┼──────────────────────────────────────────
   1 │ t3461    広島          25176  2003-09-24
   2 │ t3462    福山          47935  2003-05-15
   3 │ t3463    東広島        28654  2003-02-08
   4 │ t3464    呉            83152  2003-10-09
   5 │ t3465    尾道          42791  2003-08-04
   6 │ t3466    竹原          35687  2003-01-21

列名:
["id", "name", "population", "date_mod"]

データのサイズ: (9, 4)

人口が 50000 以上の都市の数: 3
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