{
"cells": [
{
"cell_type": "markdown",
"id": "0fbe3ea6-cadb-43fb-8882-a3afd92fd45e",
"metadata": {},
"source": [
"# ファイルの入出力"
]
},
{
"cell_type": "markdown",
"id": "4d1a198b-7111-460d-86d9-f6ec8b9471d3",
"metadata": {},
"source": [
"Polarsでは、大規模なデータセットを効率的に扱うための高速なファイル入出力操作が提供されています。データを読み込んだり書き出したりする際に、さまざまなフォーマットに対応しており、迅速なデータ処理をサポートします。この章では、Polarsを使用したファイルの入出力操作方法について詳しく説明します。"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "3eb54039-f99e-433a-9672-ece59d69c915",
"metadata": {},
"outputs": [],
"source": [
"import polars as pl\n",
"from helper.jupyter import row, capture_except"
]
},
{
"cell_type": "markdown",
"id": "fe6aaf98-5efb-4b20-b668-f2c722e3bd63",
"metadata": {},
"source": [
"## CSVファイル"
]
},
{
"cell_type": "markdown",
"id": "b2a8ef23-35b2-4543-b2b3-87f53df99260",
"metadata": {},
"source": [
"CSVファイルを読み込む際には、ファイル構造やデータの特性に応じて柔軟に操作する必要があります。本セクションでは、Polarsを使用してさまざまなCSVファイルを読み込む方法を紹介します。"
]
},
{
"cell_type": "markdown",
"id": "c3399c85-6eb0-4954-b90a-fb3b3b79934f",
"metadata": {},
"source": [
"### 読み込み"
]
},
{
"cell_type": "markdown",
"id": "99530210-ddb2-4ce9-9d28-036749738586",
"metadata": {},
"source": [
"#### ヘッダー"
]
},
{
"cell_type": "markdown",
"id": "a3454217-a299-4663-ab73-e0de8208a1b0",
"metadata": {},
"source": [
"CSVファイルには、ヘッダーの有無や、ヘッダーが複数行にわたる場合があります。以下のデータを例に、ヘッダーの扱い方について説明します。"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d5d194fc-dd60-42da-9fd5-99e43f0487da",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting data/csv_header.csv\n"
]
}
],
"source": [
"%%writefile data/csv_header.csv\n",
"A,B\n",
"a,b\n",
"0,1\n",
"2,3\n",
"4,5"
]
},
{
"cell_type": "markdown",
"id": "4545bf8f-004d-4055-a788-3c89bd14761c",
"metadata": {},
"source": [
"- `df1`: デフォルト設定では、CSVファイルをヘッダー付きとして読み込みます。この場合、データの先頭行が列の名前として解釈されます。\n",
"- `df2`: `has_header=False`を指定することで、CSVの先頭行をデータとして扱います。この場合、`new_columns`引数を使用して列名を自分で指定できます。\n",
"- `df3`: `skip_rows`引数を指定することで、最初のN行をスキップしてからデータを読み込むことができます。\n",
"- `df4`: `skip_rows_after_header`引数を指定することで、ヘッダー行の次のN行をスキップしてデータを読み込みます。\n",
"- `df5`: 最初の2行をヘッダーなしで読み込んで、それぞれの列を結合した結果を`new_columns`引数に渡し、新しい列名として適用します。この方法を使うことで、複数行のヘッダーを柔軟に扱うことができます。\n",
"\n",
"これらの方法を活用することで、CSVデータの構造に応じた柔軟な読み込みが可能になります。"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "806a8b8a-a184-4514-b7ce-ef9fccb95b99",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
" shape: (4, 2)A | B |
---|
str | str | "a" | "b" | "0" | "1" | "2" | "3" | "4" | "5" |
| \n",
" shape: (5, 2)x | y |
---|
str | str | "A" | "B" | "a" | "b" | "0" | "1" | "2" | "3" | "4" | "5" |
| | | |
"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fn = 'data/csv_header.csv'\n",
"df1 = pl.read_csv(fn)\n",
"df2 = pl.read_csv(fn, has_header=False, new_columns=['x', 'y'])\n",
"df3 = pl.read_csv(fn, skip_rows=1)\n",
"df4 = pl.read_csv(fn, skip_rows_after_header=1)\n",
"\n",
"df_header = pl.read_csv(fn, n_rows=2, has_header=False)\n",
"columns = df_header.select(pl.all().str.join('-')).row(0)\n",
"df5 = pl.read_csv(fn, has_header=False, skip_rows=2, new_columns=columns)\n",
"row(df1, df2, df3, df4, df5)"
]
},
{
"cell_type": "markdown",
"id": "f2367125-0f7d-4a17-9750-ed5e7e9f315c",
"metadata": {},
"source": [
"#### 列のデータ型\n",
"\n",
"`infer_schema`引数がデフォルト値`True`の場合、`infer_schema_length`引数で指定された先頭の行数を使用して各列のデータ型を推定します。この範囲を超えて異なるデータ型の値が出現した場合、エラーが発生します。以下のデータを例に、データ型の扱い方について説明します。"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "37b78585-296a-42b4-87ba-2e3a4f758625",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting data/csv_different_type.csv\n"
]
}
],
"source": [
"%%writefile data/csv_different_type.csv\n",
"A,B\n",
"0,1\n",
"2,3\n",
"4,5\n",
"a,5.5\n",
"10,20"
]
},
{
"cell_type": "markdown",
"id": "5cd7fc12-bfee-484f-96b5-aa816863a8d7",
"metadata": {},
"source": [
"`infer_schema_length`のデフォルト値は100ですが、以下のコードでは、`infer_schema_length`を2行に設定してエラーを発生させます。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0ca758e6-f638-43a6-96a5-88ae52fc5344",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ComputeError: could not parse `a` as dtype `i64` at column 'A' (column number 1)\n",
"\n",
"The current offset in the file is 15 bytes.\n",
"\n",
"You might want to try:\n",
"- increasing `infer_schema_length` (e.g. `infer_schema_length=10000`),\n",
"- specifying correct dtype with the `schema_overrides` argument\n",
"- setting `ignore_errors` to `True`,\n",
"- adding `a` to the `null_values` list.\n",
"\n",
"Original error: ```remaining bytes non-empty```\n"
]
}
],
"source": [
"%%capture_except\n",
"df = pl.read_csv('data/csv_different_type.csv', infer_schema_length=2)"
]
},
{
"cell_type": "markdown",
"id": "29586b17-bcc5-4404-8dab-414e083740c1",
"metadata": {},
"source": [
"エラーメッセージにはいくつかの解決方法が示されています。以下はそれらの方法を使用してデータを読み込む例です。\n",
"\n",
"- **`df1`**: `infer_schema_length`引数で推定行数を増やすことで、A列のデータ型を`str`、B列を`f64`として読み込みます。\n",
"\n",
"- **`df2`**: `infer_schema_length=None`を指定すると、すべての行を使用してデータ型を推定します。また、`null_values`引数を使用して特定の値をnullと見なすことで、A列を`i64`として読み込みます。\n",
"\n",
"- **`df3`**: `ignore_errors=True`を指定すると、推定データ型に一致しない値をnullとして読み込みます。この場合、A列とB列はどちらも`i64`になります。\n",
"\n",
"- **`df4`**: `schema_overrides`引数を使用して、各列のデータ型を明示的に指定します。さらに、`ignore_errors=True`を指定して不正な値を除外します。`schema_overrides`を使用すると、効率的なデータ型を選択でき、メモリ使用量を削減できます。\n",
"\n",
"これらの方法を使用することで、データ型の推定やエラー処理に柔軟に対応できます。"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "56a8f4a5-b9ea-4ef3-bcaa-9dc3405e119e",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" shape: (5, 2)A | B |
---|
str | f64 | "0" | 1.0 | "2" | 3.0 | "4" | 5.0 | "a" | 5.5 | "10" | 20.0 |
| \n",
" shape: (5, 2)A | B |
---|
i64 | f64 | 0 | 1.0 | 2 | 3.0 | 4 | 5.0 | null | 5.5 | 10 | 20.0 |
| \n",
" shape: (5, 2)A | B |
---|
i64 | i64 | 0 | 1 | 2 | 3 | 4 | 5 | null | null | 10 | 20 |
| \n",
" shape: (5, 2)A | B |
---|
i16 | f32 | 0 | 1.0 | 2 | 3.0 | 4 | 5.0 | null | 5.5 | 10 | 20.0 |
|
"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fn = 'data/csv_different_type.csv'\n",
"df1 = pl.read_csv(fn, infer_schema_length=1000)\n",
"df2 = pl.read_csv(fn, infer_schema_length=None, null_values=['a'])\n",
"df3 = pl.read_csv(fn, infer_schema_length=2, ignore_errors=True)\n",
"df4 = pl.read_csv(fn, schema_overrides={'A':pl.Int16, 'B':pl.Float32}, ignore_errors=True)\n",
"row(df1, df2, df3, df4)"
]
},
{
"cell_type": "markdown",
"id": "083fc595-eabd-4273-aae2-d352fa5f3686",
"metadata": {},
"source": [
"#### スペース処理\n",
"\n",
"CSVデータ内の列値に末尾のスペースが含まれている場合、Polarsの標準CSVエンジンはこれをそのまま取り込み、列データ型を`str`として解釈します。例えば、次のようなCSVデータを読み込む場合を考えます:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "abbd1bbf-3693-4131-9112-2fd798e27ef5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting data/csv_trailing_space.csv\n"
]
}
],
"source": [
"%%writefile data/csv_trailing_space.csv\n",
"str,int,float\n",
"日本語 ,4 ,5.67 \n",
"abc ,5 ,1.23 "
]
},
{
"cell_type": "markdown",
"id": "4b64e71e-c51f-4708-aaa3-2d33e376a64f",
"metadata": {},
"source": [
"このデータを読み込むと、Polarsの標準エンジンと`use_pyarrow=True`を指定した場合で動作が異なります:\n",
"\n",
"* `df1`: Polarsの標準エンジンでは、すべての列が文字列(`str`)として扱われます。\n",
"* `df2`: `use_pyarrow=True`を指定すると、数値列(`int`, `float`)が適切に解釈されます。"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "0960cef2-d7c0-4a0d-859f-9704ba0ee71a",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" shape: (2, 3)str | int | float |
---|
str | str | str | "日本語 " | "4 " | "5.67 " | "abc " | "5 " | "1.23 " |
| \n",
" shape: (2, 3)str | int | float |
---|
str | i64 | f64 | "日本語 " | 4 | 5.67 | "abc " | 5 | 1.23 |
|
"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fn = 'data/csv_trailing_space.csv'\n",
"df1 = pl.read_csv(fn)\n",
"df2 = pl.read_csv(fn, use_pyarrow=True)\n",
"row(df1, df2)"
]
},
{
"cell_type": "markdown",
"id": "e8bfb66e-15dd-451e-86fd-a7e1a4067a9e",
"metadata": {},
"source": [
"Polarsでは文字列列を自動的に数値型に変換するカスタム関数を作成することで、スペースを取り除きつつ適切にキャストできます。以下はその例です。\n",
"\n",
"1. `s.str.strip_chars()` を使用して余分なスペースを削除。\n",
"2. `.cast(int_type)` を試みて、整数型に変換できるかを確認。\n",
"3. 整数型への変換が失敗した場合は `.cast(float_type)` を試みて、浮動小数型に変換。\n",
"4. どちらのキャストも失敗した場合には元の文字列型を返す。"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "751d575f-140c-4fb6-ba82-77be361d9ba4",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"
shape: (2, 3)str | int | float |
---|
str | i64 | f64 |
"日本語 " | 4 | 5.67 |
"abc " | 5 | 1.23 |
"
],
"text/plain": [
"shape: (2, 3)\n",
"┌─────────┬─────┬───────┐\n",
"│ str ┆ int ┆ float │\n",
"│ --- ┆ --- ┆ --- │\n",
"│ str ┆ i64 ┆ f64 │\n",
"╞═════════╪═════╪═══════╡\n",
"│ 日本語 ┆ 4 ┆ 5.67 │\n",
"│ abc ┆ 5 ┆ 1.23 │\n",
"└─────────┴─────┴───────┘"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from polars import selectors as cs\n",
"from polars.exceptions import InvalidOperationError\n",
"\n",
"# この関数はhelper/polars.pyにあります。\n",
"def try_cast_to_number(s, int_type=pl.Int64, float_type=pl.Float64):\n",
" try:\n",
" return s.str.strip_chars().cast(int_type)\n",
" except InvalidOperationError:\n",
" try:\n",
" return s.str.strip_chars().cast(float_type)\n",
" except InvalidOperationError:\n",
" return s\n",
"\n",
"df1.with_columns(cs.string().map_batches(try_cast_to_number))"
]
},
{
"cell_type": "markdown",
"id": "cb9a573f-380d-4ae6-b0b2-3d282531ccf2",
"metadata": {},
"source": [
"#### 複数のファイルを読み込み\n",
"\n",
"次のコードを実行して、stockデータを`data/stock`フォルダにダウンロードします。"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "5e0c94c4-b276-4f86-b19d-ae53512a6736",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"data/stock exists, please delete and try again.\n"
]
}
],
"source": [
"from helper.utils import download_folder_from_github, print_folder_structure\n",
"download_folder_from_github(\"https://github.com/jeroenjanssens/python-polars-the-definitive-guide/tree/main/data/stock\", \"data/stock\")"
]
},
{
"cell_type": "markdown",
"id": "d6c5b43d-2fd3-430a-91dd-13723e2b4821",
"metadata": {},
"source": [
"ダウンロードしたデータのフォルダ構造は次のようなものです。"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "2d71d5c4-f567-4809-bf6f-d3313eb00d20",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"|-- asml\n",
" |-- 1999.csv\n",
" |-- 2000.csv\n",
" |-- 2001.csv\n",
" |-- ...\n",
"|-- nvda\n",
" |-- 1999.csv\n",
" |-- 2000.csv\n",
" |-- 2001.csv\n",
" |-- ...\n",
"|-- tsm\n",
" |-- 1999.csv\n",
" |-- 2000.csv\n",
" |-- 2001.csv\n",
" |-- ...\n"
]
}
],
"source": [
"print_folder_structure(\"data/stock\", max_file_count=3)"
]
},
{
"cell_type": "markdown",
"id": "b7978d93-5952-47f6-b0d7-ae24177634fb",
"metadata": {},
"source": [
"上のすべてのCSVファイルを一気に読み込みするのは、ファイルパスにワイルドカードを使用します。"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "ac6ea392-f41c-4f4e-ab41-2536fd4690f7",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"
shape: (18_476, 8)symbol | date | open | high | low | close | adj close | volume |
---|
str | str | f64 | f64 | f64 | f64 | f64 | i64 |
"ASML" | "1999-01-04" | 11.765625 | 12.28125 | 11.765625 | 12.140625 | 7.522523 | 1801867 |
"ASML" | "1999-01-05" | 11.859375 | 14.25 | 11.71875 | 13.96875 | 8.655257 | 8241600 |
"ASML" | "1999-01-06" | 14.25 | 17.601563 | 14.203125 | 16.875 | 10.456018 | 16400267 |
"ASML" | "1999-01-07" | 14.742188 | 17.8125 | 14.53125 | 16.851563 | 10.441495 | 17722133 |
"ASML" | "1999-01-08" | 16.078125 | 16.289063 | 15.023438 | 15.796875 | 9.787995 | 10696000 |
… | … | … | … | … | … | … | … |
"TSM" | "2023-06-26" | 102.019997 | 103.040001 | 100.089996 | 100.110001 | 99.125954 | 8560000 |
"TSM" | "2023-06-27" | 101.150002 | 102.790001 | 100.019997 | 102.080002 | 101.076591 | 9732000 |
"TSM" | "2023-06-28" | 100.5 | 101.879997 | 100.220001 | 100.919998 | 99.927986 | 8160900 |
"TSM" | "2023-06-29" | 101.339996 | 101.519997 | 100.019997 | 100.639999 | 99.650742 | 7383900 |
"TSM" | "2023-06-30" | 101.400002 | 101.889999 | 100.410004 | 100.919998 | 99.927986 | 11701700 |
"
],
"text/plain": [
"shape: (18_476, 8)\n",
"┌────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬──────────┐\n",
"│ symbol ┆ date ┆ open ┆ high ┆ low ┆ close ┆ adj close ┆ volume │\n",
"│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │\n",
"│ str ┆ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ i64 │\n",
"╞════════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╪══════════╡\n",
"│ ASML ┆ 1999-01-04 ┆ 11.765625 ┆ 12.28125 ┆ 11.765625 ┆ 12.140625 ┆ 7.522523 ┆ 1801867 │\n",
"│ ASML ┆ 1999-01-05 ┆ 11.859375 ┆ 14.25 ┆ 11.71875 ┆ 13.96875 ┆ 8.655257 ┆ 8241600 │\n",
"│ ASML ┆ 1999-01-06 ┆ 14.25 ┆ 17.601563 ┆ 14.203125 ┆ 16.875 ┆ 10.456018 ┆ 16400267 │\n",
"│ ASML ┆ 1999-01-07 ┆ 14.742188 ┆ 17.8125 ┆ 14.53125 ┆ 16.851563 ┆ 10.441495 ┆ 17722133 │\n",
"│ ASML ┆ 1999-01-08 ┆ 16.078125 ┆ 16.289063 ┆ 15.023438 ┆ 15.796875 ┆ 9.787995 ┆ 10696000 │\n",
"│ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … │\n",
"│ TSM ┆ 2023-06-26 ┆ 102.019997 ┆ 103.040001 ┆ 100.089996 ┆ 100.110001 ┆ 99.125954 ┆ 8560000 │\n",
"│ TSM ┆ 2023-06-27 ┆ 101.150002 ┆ 102.790001 ┆ 100.019997 ┆ 102.080002 ┆ 101.076591 ┆ 9732000 │\n",
"│ TSM ┆ 2023-06-28 ┆ 100.5 ┆ 101.879997 ┆ 100.220001 ┆ 100.919998 ┆ 99.927986 ┆ 8160900 │\n",
"│ TSM ┆ 2023-06-29 ┆ 101.339996 ┆ 101.519997 ┆ 100.019997 ┆ 100.639999 ┆ 99.650742 ┆ 7383900 │\n",
"│ TSM ┆ 2023-06-30 ┆ 101.400002 ┆ 101.889999 ┆ 100.410004 ┆ 100.919998 ┆ 99.927986 ┆ 11701700 │\n",
"└────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴──────────┘"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_stock = pl.read_csv('data/stock/**/*.csv', try_parse_dates=True)\n",
"df_stock"
]
},
{
"cell_type": "markdown",
"id": "9942a2b6-2b7a-4432-a1f6-18e67503b4dc",
"metadata": {},
"source": [
"この例では各個CSVファイル中のデータにはファイル名の情報が含まれているため、ファイル名を列として作成する必要がないですが、ファイル名を結果に追加したい場合は、`include_file_paths`引数を使います。ファイル名列の名前はこの引数で指定された列名になります。`read_csv()`はまだこの引数をサポートしていないため、次の例では遅延演算の`scan_csv()`関数を使います。この関数のリターン値は`LazyFrame`で、`collect()`メソッドを使って実際のデータを読み出します。"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "6acae754-73c1-49bc-bc5d-197306effacf",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"naive plan: (run LazyFrame.explain(optimized=True) to see the optimized plan)\n",
" \n",
" Csv SCAN [data\\stock\\asml\\1999.csv, ... 74 other sources]
PROJECT */9 COLUMNS
"
],
"text/plain": [
""
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_stock = pl.scan_csv('data/stock/**/*.csv', try_parse_dates=True, include_file_paths=\"path\")\n",
"df_stock"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "be45b0b1-6732-4ca6-a168-e0e92ac42dda",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"
shape: (18_476, 9)symbol | date | open | high | low | close | adj close | volume | path |
---|
str | date | f64 | f64 | f64 | f64 | f64 | i64 | str |
"ASML" | 1999-01-04 | 11.765625 | 12.28125 | 11.765625 | 12.140625 | 7.522523 | 1801867 | "data\\stock\\asml\\1999.csv" |
"ASML" | 1999-01-05 | 11.859375 | 14.25 | 11.71875 | 13.96875 | 8.655257 | 8241600 | "data\\stock\\asml\\1999.csv" |
"ASML" | 1999-01-06 | 14.25 | 17.601563 | 14.203125 | 16.875 | 10.456018 | 16400267 | "data\\stock\\asml\\1999.csv" |
"ASML" | 1999-01-07 | 14.742188 | 17.8125 | 14.53125 | 16.851563 | 10.441495 | 17722133 | "data\\stock\\asml\\1999.csv" |
"ASML" | 1999-01-08 | 16.078125 | 16.289063 | 15.023438 | 15.796875 | 9.787995 | 10696000 | "data\\stock\\asml\\1999.csv" |
… | … | … | … | … | … | … | … | … |
"TSM" | 2023-06-26 | 102.019997 | 103.040001 | 100.089996 | 100.110001 | 99.125954 | 8560000 | "data\\stock\\tsm\\2023.csv" |
"TSM" | 2023-06-27 | 101.150002 | 102.790001 | 100.019997 | 102.080002 | 101.076591 | 9732000 | "data\\stock\\tsm\\2023.csv" |
"TSM" | 2023-06-28 | 100.5 | 101.879997 | 100.220001 | 100.919998 | 99.927986 | 8160900 | "data\\stock\\tsm\\2023.csv" |
"TSM" | 2023-06-29 | 101.339996 | 101.519997 | 100.019997 | 100.639999 | 99.650742 | 7383900 | "data\\stock\\tsm\\2023.csv" |
"TSM" | 2023-06-30 | 101.400002 | 101.889999 | 100.410004 | 100.919998 | 99.927986 | 11701700 | "data\\stock\\tsm\\2023.csv" |
"
],
"text/plain": [
"shape: (18_476, 9)\n",
"┌────────┬────────────┬────────────┬────────────┬───┬────────────┬────────────┬──────────┬──────────────────────────┐\n",
"│ symbol ┆ date ┆ open ┆ high ┆ … ┆ close ┆ adj close ┆ volume ┆ path │\n",
"│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │\n",
"│ str ┆ date ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ i64 ┆ str │\n",
"╞════════╪════════════╪════════════╪════════════╪═══╪════════════╪════════════╪══════════╪══════════════════════════╡\n",
"│ ASML ┆ 1999-01-04 ┆ 11.765625 ┆ 12.28125 ┆ … ┆ 12.140625 ┆ 7.522523 ┆ 1801867 ┆ data\\stock\\asml\\1999.csv │\n",
"│ ASML ┆ 1999-01-05 ┆ 11.859375 ┆ 14.25 ┆ … ┆ 13.96875 ┆ 8.655257 ┆ 8241600 ┆ data\\stock\\asml\\1999.csv │\n",
"│ ASML ┆ 1999-01-06 ┆ 14.25 ┆ 17.601563 ┆ … ┆ 16.875 ┆ 10.456018 ┆ 16400267 ┆ data\\stock\\asml\\1999.csv │\n",
"│ ASML ┆ 1999-01-07 ┆ 14.742188 ┆ 17.8125 ┆ … ┆ 16.851563 ┆ 10.441495 ┆ 17722133 ┆ data\\stock\\asml\\1999.csv │\n",
"│ ASML ┆ 1999-01-08 ┆ 16.078125 ┆ 16.289063 ┆ … ┆ 15.796875 ┆ 9.787995 ┆ 10696000 ┆ data\\stock\\asml\\1999.csv │\n",
"│ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … │\n",
"│ TSM ┆ 2023-06-26 ┆ 102.019997 ┆ 103.040001 ┆ … ┆ 100.110001 ┆ 99.125954 ┆ 8560000 ┆ data\\stock\\tsm\\2023.csv │\n",
"│ TSM ┆ 2023-06-27 ┆ 101.150002 ┆ 102.790001 ┆ … ┆ 102.080002 ┆ 101.076591 ┆ 9732000 ┆ data\\stock\\tsm\\2023.csv │\n",
"│ TSM ┆ 2023-06-28 ┆ 100.5 ┆ 101.879997 ┆ … ┆ 100.919998 ┆ 99.927986 ┆ 8160900 ┆ data\\stock\\tsm\\2023.csv │\n",
"│ TSM ┆ 2023-06-29 ┆ 101.339996 ┆ 101.519997 ┆ … ┆ 100.639999 ┆ 99.650742 ┆ 7383900 ┆ data\\stock\\tsm\\2023.csv │\n",
"│ TSM ┆ 2023-06-30 ┆ 101.400002 ┆ 101.889999 ┆ … ┆ 100.919998 ┆ 99.927986 ┆ 11701700 ┆ data\\stock\\tsm\\2023.csv │\n",
"└────────┴────────────┴────────────┴────────────┴───┴────────────┴────────────┴──────────┴──────────────────────────┘"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_stock.collect()"
]
},
{
"cell_type": "markdown",
"id": "7f5205b9-1d84-4feb-99a6-9bb53a2b64e7",
"metadata": {},
"source": [
"### 書き出し\n",
"\n",
"`DataFrame.write_csv()` を使用して、データフレームをCSVファイルとして出力できます。"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "4b437ade-7944-45ea-bfeb-ca1cff8ef1ee",
"metadata": {},
"outputs": [],
"source": [
"df1.write_csv('data/csv_output_utf8.csv')"
]
},
{
"cell_type": "markdown",
"id": "c326bc5a-fdea-4c62-9916-aed7271f6905",
"metadata": {},
"source": [
"`write_csv()`メソッドでは、`include_header`、`separator`、`line_terminator` などの引数を使って、CSVのフォーマットを細かく指定できます。ただし、エンコードを直接指定する引数はありません。そのため、一度CSVデータを `StringIO` に出力し、それを使用してSHIFT-JISエンコードのファイルとして保存する方法を取ります。以下はそのコード例です:"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "669b4a4b-d73c-4b13-a00a-56046b335ec4",
"metadata": {},
"outputs": [],
"source": [
"import io\n",
"\n",
"buf = io.StringIO()\n",
"df1.write_csv(buf)\n",
"\n",
"with open('data/csv_output_shiftjis.csv', 'w', encoding='shift-jis') as f:\n",
" f.write(buf.getvalue())"
]
},
{
"cell_type": "markdown",
"id": "73d63632-f657-4fdb-ace7-750b8bd84f11",
"metadata": {},
"source": [
"## Excelファイル\n",
"\n",
"`read_excel()`と`DataFrame.write_excel()`を使用してExcelファイルの入出力を行います。Excelファイルの読み込みには、`calamine`、`xlsx2csv`、`openpyxl`の3つのエンジンが利用可能で、デフォルトの`calamine`は最も高速です。書き出しには`xlsxwriter`ライブラリを使用します。次のコマンドで必要なライブラリをインストールします。\n",
"\n",
"```\n",
"conda install fastexcel xlsxwriter\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "f5d9339a-fd2e-4768-a3d8-750ae49ebf0c",
"metadata": {},
"source": [
"### 読み込み"
]
},
{
"cell_type": "markdown",
"id": "fb779f48-09db-49a6-b507-48d071893848",
"metadata": {},
"source": [
"次のコードは、指定されたシートからデータを読み込みます。`sheet_id`引数には、読み込みたいシート番号(1から始まる整数)或いはシート番号のリストを指定します。0の場合はすべてのシートを読み込みます。複数のシートを読み込む場合、シート名をキー、データフレームを値とする辞書を返します。`sheet_names`引数を使用して、シート名で読み込み対象のシートを指定することもできます。"
]
},
{
"cell_type": "code",
"execution_count": 59,
"id": "66114fe8-8a09-4f53-90da-f4f663f232a3",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
" | \n",
" shape: (3, 3)x | y | z |
---|
f64 | f64 | f64 | 1.0 | 1.0 | 3.1 | 1.2 | 2.1 | 4.3 | 3.2 | 4.3 | 5.4 |
|
"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fn = 'data/xlsx_example.xlsx'\n",
"df1, df2 = pl.read_excel(fn, sheet_id=[1, 2]).values()\n",
"row(df1, df2)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"id": "b07ef5ea-c788-4fff-8483-8cbb2ed384e9",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
" | \n",
" shape: (3, 3)x | y | z |
---|
f64 | f64 | f64 | 1.0 | 1.0 | 3.1 | 1.2 | 2.1 | 4.3 | 3.2 | 4.3 | 5.4 |
| \n",
" shape: (4, 2)A | B |
---|
str | str | "a" | "b" | "0" | "1" | "2" | "3" | "4" | "5" |
|
"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"df1, df2, df3 = pl.read_excel(fn, sheet_id=0).values()\n",
"row(df1, df2, df3)"
]
},
{
"cell_type": "markdown",
"id": "cf345767-e675-4b09-b993-831106c5c8fe",
"metadata": {},
"source": [
"シート`Sheet3`には2行のヘッダーがあるため、直接読み込むと、2行目のヘッダーがデータとして扱われ、すべての列のデータ型が文字列になります。この問題を解決するために、`read_options`引数を使用してExcelエンジンに渡す設定を調整できます。\n",
"\n",
"以下のコードでは、1回目の`read_excel()`で`n_rows=2`と`header_row=None`を指定し、先頭の2行をデータとして読み込んで、文字列結合し列名`columns`を計算します。2回目の読み込みでは、`skip_rows=2`でヘッダーをスキップし、`column_names=columns`で列名を指定します。"
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "52b4ccac-fc1b-46e5-906f-27d46904e492",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
"shape: (3, 2)\n",
"┌─────┬─────┐\n",
"│ A-a ┆ B-b │\n",
"│ --- ┆ --- │\n",
"│ i64 ┆ i64 │\n",
"╞═════╪═════╡\n",
"│ 0 ┆ 1 │\n",
"│ 2 ┆ 3 │\n",
"│ 4 ┆ 5 │\n",
"└─────┴─────┘"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_header = pl.read_excel(fn, sheet_id=3, read_options=dict(n_rows=2, header_row=None))\n",
"columns = df_header.select(pl.all().str.join('-')).row(0)\n",
"df3 = pl.read_excel(fn, sheet_id=3, read_options=dict(skip_rows=2, column_names=columns))\n",
"df3"
]
},
{
"cell_type": "markdown",
"id": "be25894a-7ea4-4458-b12e-d1e33d2e0934",
"metadata": {},
"source": [
"`calamine`エンジンを使用する場合、`read_options`に渡す引数は次のようになります。"
]
},
{
"cell_type": "code",
"execution_count": 63,
"id": "c86a3393-b28d-41dc-8430-1073476cf888",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[1;31mSignature:\u001b[0m\n",
"\u001b[0mExcelReader\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mload_sheet\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0midx_or_name\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'int | str'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[1;33m*\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mheader_row\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'int | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mcolumn_names\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'list[str] | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mskip_rows\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'int | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mn_rows\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'int | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mschema_sample_rows\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'int | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1000\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mdtype_coercion\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m\"Literal['coerce', 'strict']\"\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'coerce'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0muse_columns\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'list[str] | list[int] | str | Callable[[ColumnInfo], bool] | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m \u001b[0mdtypes\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m'DType | DTypeMap | None'\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\n",
"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m->\u001b[0m \u001b[1;34m'ExcelSheet'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mDocstring:\u001b[0m\n",
"Loads a sheet lazily by index or name.\n",
"\n",
":param idx_or_name: The index (starting at 0) or the name of the sheet to load.\n",
":param header_row: The index of the row containing the column labels, default index is 0.\n",
" If `None`, the sheet does not have any column labels.\n",
" Any rows before the `header_row` will be automatically skipped.\n",
":param column_names: Overrides headers found in the document.\n",
" If `column_names` is used, `header_row` will be ignored.\n",
":param n_rows: Specifies how many rows should be loaded.\n",
" If `None`, all rows are loaded\n",
":param skip_rows: Specifies how many rows should be skipped after the `header_row`.\n",
" Any rows before the `header_row` are automatically skipped.\n",
" If `header_row` is `None`:\n",
" - if `skip_rows` is `None` (default): it skips all empty rows\n",
" at the beginning of the sheet.\n",
" - if `skip_rows` is a number, it skips the specified number\n",
" of rows from the start of the sheet.\n",
":param schema_sample_rows: Specifies how many rows should be used to determine\n",
" the dtype of a column.\n",
" If `None`, all rows will be used.\n",
":param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default)\n",
" will try to coerce different dtypes in a column to the same one,\n",
" whereas `strict` will raise an error in case a column contains\n",
" several dtypes. Note that this only applies to columns whose dtype\n",
" is guessed, i.e. not specified via `dtypes`.\n",
":param use_columns: Specifies the columns to use. Can either be:\n",
" - `None` to select all columns\n",
" - A list of strings and ints, the column names and/or indices\n",
" (starting at 0)\n",
" - A string, a comma separated list of Excel column letters and column\n",
" ranges (e.g. `“A:E”` or `“A,C,E:F”`, which would result in\n",
" `A,B,C,D,E` and `A,C,E,F`)\n",
" - A callable, a function that takes a column and returns a boolean\n",
" indicating whether the column should be used\n",
":param dtypes: An optional dtype (for all columns)\n",
" or dict of dtypes with keys as column indices or names.\n",
"\u001b[1;31mFile:\u001b[0m c:\\micromamba\\envs\\cad\\lib\\site-packages\\fastexcel\\__init__.py\n",
"\u001b[1;31mType:\u001b[0m function"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from fastexcel import ExcelReader\n",
"ExcelReader.load_sheet?"
]
},
{
"cell_type": "markdown",
"id": "e98a10c5-24ea-4a65-b6ef-2689502a02f7",
"metadata": {},
"source": [
"### 書き出し\n",
"\n",
"`DataFrame.write_excel()`を使って、指定したファイル名とシート名にデータを書き出します。複数のデータフレームを同じファイルの別々のシートに書き出す場合、次のコードのように`Workbook`オブジェクトを作成し、そのオブジェクトに対して複数回`.write_excel()`を呼び出します。"
]
},
{
"cell_type": "code",
"execution_count": 73,
"id": "c491c31b-1821-4a22-8f53-88b67682aa9d",
"metadata": {},
"outputs": [],
"source": [
"import xlsxwriter\n",
"\n",
"with xlsxwriter.Workbook(\"data/xlsx_example_output.xlsx\") as wb:\n",
" df1.write_excel(wb, \"df1\")\n",
" df2.write_excel(wb, \"df2\")\n",
" df3.write_excel(wb, \"df3\") "
]
},
{
"cell_type": "markdown",
"id": "3e826bf1-08d1-40ef-b1a2-a1030c8e63f0",
"metadata": {},
"source": [
"## バイナリファイル\n",
"\n",
"データフレーム操作を効率的に行うために、Polarsはさまざまなバイナリファイルフォーマットをサポートしています。特に、`ipc`(Inter-Process Communication)と`parquet`は、データの保存や転送に適したフォーマットです。\n",
"\n",
"1. **IPC(Inter-Process Communication)**:\n",
" - IPCフォーマットは、プロセス間での高速なデータ交換を目的としたバイナリ形式です。\n",
" - Polarsでは、データフレームを効率的に保存および読み込むために使用され、特に同一のメモリ空間内で異なるプロセスがデータをやり取りする際に便利です。\n",
" - 高速なシリアル化とデシリアル化が可能で、大きなデータセットの転送に最適です。\n",
"\n",
"2. **Parquet**:\n",
" - Parquetは、列指向のデータフォーマットで、大規模なデータを効率的に保存できるように設計されています。\n",
" - 特に圧縮効率が高く、読み込み時には必要な列だけを効率的に取得できるため、ストレージとI/Oパフォーマンスを最適化できます。\n",
" - 分散処理環境(例: Apache Spark)でよく使用される形式で、データ分析やETLパイプラインで広く利用されています。\n",
"\n",
"どちらのフォーマットも、Polarsで高速なデータ処理を行う際に重要な役割を果たします。`ipc`は主にプロセス間通信で使用され、`parquet`はストレージと分析の効率化に優れています。\n",
"\n",
"`ipc`と`parquet`フォーマットに対して、`DataFrame`データの読み込みと書き出しには`read_*()`と`write_*()`を使用します。一方、`LazyFrame`データの操作には`scan_*()`と`sink_*()`を使用します。それぞれの関数とメソッドについて以下に説明します。\n",
"\n",
"- **`read_ipc()` と `read_parquet()` 関数**: バイナリファイルからデータを読み込み、`DataFrame`オブジェクトを取得します。\n",
"- **`DataFrame` の `write_ipc()` と `write_parquet()` メソッド**: `DataFrame`オブジェクトをバイナリファイルに書き出します。\n",
"- **`scan_ipc()` と `scan_parquet()` 関数**: バイナリファイルからデータを遅延評価形式で読み込み、`LazyFrame`オブジェクトを取得します。\n",
"- **`LazyFrame` の `sink_ipc()` と `sink_parquet()` メソッド**: `LazyFrame`オブジェクトをバイナリファイルストリームに書き出します。\n",
"\n",
"既にメモリ上にデータがある`DataFrame`のデータをファイルに保存する場合は`write_*()`メソッドを使いますが、遅延評価を使用する`LazyFrame`のデータをファイルに書き出す場合は、`sink_*()`メソッドを使用します。このメソッドは一度にすべてのデータを処理するのではなく、チャンク単位でデータを処理するため、データのサイズがメモリより大きくても問題なく処理できます。\n",
"\n",
"次のコードは、`scan_csv()`関数と`sink_ipc()`メソッドを使って、複数のCSVファイルを一つのIPCファイルに変換する処理です。これにより、大量のCSVデータをメモリに負荷をかけることなく効率的にIPCフォーマットに変換でき、後で高速に読み込むことが可能になります。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8e65de9d-67a5-4133-95a5-f3264d00c49b",
"metadata": {},
"outputs": [],
"source": [
"df_stock = pl.scan_csv('data/stock/**/*.csv', try_parse_dates=True)\n",
"df_stock.sink_ipc('data/stock.arrow')"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "b93b1aa4-cd83-4859-acde-63c9e469538d",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"
shape: (18_476, 8)symbol | date | open | high | low | close | adj close | volume |
---|
str | date | f64 | f64 | f64 | f64 | f64 | i64 |
"ASML" | 1999-01-04 | 11.765625 | 12.28125 | 11.765625 | 12.140625 | 7.522523 | 1801867 |
"ASML" | 1999-01-05 | 11.859375 | 14.25 | 11.71875 | 13.96875 | 8.655257 | 8241600 |
"ASML" | 1999-01-06 | 14.25 | 17.601563 | 14.203125 | 16.875 | 10.456018 | 16400267 |
"ASML" | 1999-01-07 | 14.742188 | 17.8125 | 14.53125 | 16.851563 | 10.441495 | 17722133 |
"ASML" | 1999-01-08 | 16.078125 | 16.289063 | 15.023438 | 15.796875 | 9.787995 | 10696000 |
… | … | … | … | … | … | … | … |
"TSM" | 2023-06-26 | 102.019997 | 103.040001 | 100.089996 | 100.110001 | 99.125954 | 8560000 |
"TSM" | 2023-06-27 | 101.150002 | 102.790001 | 100.019997 | 102.080002 | 101.076591 | 9732000 |
"TSM" | 2023-06-28 | 100.5 | 101.879997 | 100.220001 | 100.919998 | 99.927986 | 8160900 |
"TSM" | 2023-06-29 | 101.339996 | 101.519997 | 100.019997 | 100.639999 | 99.650742 | 7383900 |
"TSM" | 2023-06-30 | 101.400002 | 101.889999 | 100.410004 | 100.919998 | 99.927986 | 11701700 |
"
],
"text/plain": [
"shape: (18_476, 8)\n",
"┌────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬──────────┐\n",
"│ symbol ┆ date ┆ open ┆ high ┆ low ┆ close ┆ adj close ┆ volume │\n",
"│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │\n",
"│ str ┆ date ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ i64 │\n",
"╞════════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╪══════════╡\n",
"│ ASML ┆ 1999-01-04 ┆ 11.765625 ┆ 12.28125 ┆ 11.765625 ┆ 12.140625 ┆ 7.522523 ┆ 1801867 │\n",
"│ ASML ┆ 1999-01-05 ┆ 11.859375 ┆ 14.25 ┆ 11.71875 ┆ 13.96875 ┆ 8.655257 ┆ 8241600 │\n",
"│ ASML ┆ 1999-01-06 ┆ 14.25 ┆ 17.601563 ┆ 14.203125 ┆ 16.875 ┆ 10.456018 ┆ 16400267 │\n",
"│ ASML ┆ 1999-01-07 ┆ 14.742188 ┆ 17.8125 ┆ 14.53125 ┆ 16.851563 ┆ 10.441495 ┆ 17722133 │\n",
"│ ASML ┆ 1999-01-08 ┆ 16.078125 ┆ 16.289063 ┆ 15.023438 ┆ 15.796875 ┆ 9.787995 ┆ 10696000 │\n",
"│ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … │\n",
"│ TSM ┆ 2023-06-26 ┆ 102.019997 ┆ 103.040001 ┆ 100.089996 ┆ 100.110001 ┆ 99.125954 ┆ 8560000 │\n",
"│ TSM ┆ 2023-06-27 ┆ 101.150002 ┆ 102.790001 ┆ 100.019997 ┆ 102.080002 ┆ 101.076591 ┆ 9732000 │\n",
"│ TSM ┆ 2023-06-28 ┆ 100.5 ┆ 101.879997 ┆ 100.220001 ┆ 100.919998 ┆ 99.927986 ┆ 8160900 │\n",
"│ TSM ┆ 2023-06-29 ┆ 101.339996 ┆ 101.519997 ┆ 100.019997 ┆ 100.639999 ┆ 99.650742 ┆ 7383900 │\n",
"│ TSM ┆ 2023-06-30 ┆ 101.400002 ┆ 101.889999 ┆ 100.410004 ┆ 100.919998 ┆ 99.927986 ┆ 11701700 │\n",
"└────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴──────────┘"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_stock = pl.read_ipc('data/stock.arrow')\n",
"df_stock"
]
},
{
"cell_type": "markdown",
"id": "cb401aca-9e57-4d88-b001-5ece3cb7ec3f",
"metadata": {},
"source": [
"上記の関数では、1つのデータフレームが1つのファイルに対応する形で処理されますが、`write_ipc_stream()`と`read_ipc_stream()`を使用することで、複数のデータフレームを順番に1つのファイルに書き出し、またそれを読み込むことができます。次のコードは、バイナリファイル`f`に2つのデータフレームを書き出す例です。"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "9624316d-a8c3-44a1-8996-e087ce6b51c4",
"metadata": {},
"outputs": [],
"source": [
"df1 = pl.DataFrame({\"a\":[1, 2, 3], \"b\":[\"xx\", \"yyy\", \"zzzz\"]})\n",
"df2 = pl.DataFrame({\"x\":[3.0, 4.0, 6.0, 7.0], \"y\":[1.0, 2.0, 3.0, 4.0], \"z\":[0.0, 0.1, 0.2, 0.3]})\n",
"\n",
"with open('data/stream_test.arrow', 'wb') as f:\n",
" df1.write_ipc_stream(f)\n",
" df2.write_ipc_stream(f)"
]
},
{
"cell_type": "markdown",
"id": "e66a8090-7b6c-44c5-b3d7-562e8834f064",
"metadata": {},
"source": [
"次のコードで、バイナリファイルから順番にデータフレームを読み込むことができます。\n",
"\n",
"```{note}\n",
"Polars 1.20.0までのバージョンでは、デフォルト値`use_pyarrow=False`を使用した場合、このコードは正しく動作しません。`use_pyarrow=True`を指定する必要があります。\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 47,
"id": "6b32662e-dd16-4f9a-9647-737b4d9b161f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True True\n"
]
}
],
"source": [
"with open('data/stream_test.arrow', 'rb') as f:\n",
" df1_r = pl.read_ipc_stream(f, use_pyarrow=True)\n",
" df2_r = pl.read_ipc_stream(f, use_pyarrow=True)\n",
"\n",
"print(df1.equals(df1_r), df2.equals(df2_r))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}