pandas から SQLite を読む
次のコードを実行したときの出力として、正しいものを1つ選べ。
import pandas as pd
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table t (x integer)")
con.executemany("insert into t values (?)", [(1,), (2,), (3,)])
df = pd.read_sql("select sum(x) as s from t", con)
print(int(df["s"][0]))
- A
3 - B
1 - C
6 - D
sum(x)
正解と解説を見る
正解:C
pd.read_sql(SQL, 接続) で、SQL の実行結果を DataFrame に読み込める。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import pandas as pd` | — |
| 2 | `import sqlite3` | — |
| 3 | `con = sqlite3.connect(":memory:")` | — |
| 4 | `con.execute("create table t (x integer)")` | — |
| 5 | `con.executemany("insert into t values (?)", […` | — |
| 6 | `df = pd.read_sql("select sum(x) as s from t",…` | df = DataFrame(1行×1列) |
| 7 | `print(int(df["s"][0]))` | df = DataFrame(1行×1列) |
| 結果 | 実際の出力 | 6 |
- A
誤り。行数であり、合計ではない。
- B
誤り。先頭の値。
- C
正しい。SQL の結果が
DataFrameとして得られる。 - D
誤り。列名ではなく、列の値を表示する。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。