メインコンテンツへスキップ
メインコンテンツへスキップ

DataStore クラスリファレンス

このリファレンスでは、DataStore API の中核となるクラスについて解説します。

DataStore

データ操作を行うための、DataFrame に似た主要なクラスです。

from chdb.datastore import DataStore

コンストラクタ

DataStore(data=None, columns=None, index=None, dtype=None, copy=None)

パラメータ:

パラメータ説明
datadict/list/DataFrame/DataStore入力データ
columnslistカラム名
indexIndex行の索引
dtypedictカラムのデータ型
copyboolデータをコピーするかどうか

使用例:

# From dictionary
ds = DataStore({'a': [1, 2, 3], 'b': ['x', 'y', 'z']})

# From pandas DataFrame
import pandas as pd
ds = DataStore(pd.DataFrame({'a': [1, 2, 3]}))

# Empty DataStore
ds = DataStore()

Properties

PropertyTypeDescription
columnsIndexカラム名
dtypesSeriesカラムのデータ型
shapetuple(行数, カラム数)
sizeint要素の総数
ndimint次元数 (2)
emptyboolDataFrame が空かどうか
valuesndarray内部データ(NumPy 配列)
indexIndex行インデックス
TDataStore転置
axeslist軸の一覧

ファクトリーメソッド

MethodDescription
uri(uri)URI からの汎用ファクトリーメソッド
from_file(path, ...)ファイルから作成
from_df(df)pandas DataFrame から作成
from_s3(url, ...)S3 から作成
from_gcs(url, ...)Google Cloud Storage から作成
from_azure(url, ...)Azure Blob から作成
from_mysql(...)MySQL から作成
from_postgresql(...)PostgreSQL から作成
from_clickhouse(...)ClickHouse から作成
from_mongodb(...)MongoDB から作成
from_sqlite(...)SQLite から作成
from_iceberg(path)Iceberg テーブルから作成
from_delta(path)Delta Lake から作成
from_numbers(n)連番データで作成
from_random(rows, cols)ランダムなデータで作成
run_sql(query)SQL クエリから作成

詳細は ファクトリーメソッド を参照してください。

クエリメソッド

MethodReturnsDescription
select(*cols)DataStoreカラムを選択
filter(condition)DataStore行を絞り込み
where(condition)DataStorefilter のエイリアス
sort(*cols, ascending=True)DataStore行をソート
orderby(*cols)DataStoresort のエイリアス
limit(n)DataStore行数を制限
offset(n)DataStore行をスキップ
distinct(subset=None)DataStore重複を削除
groupby(*cols)LazyGroupBy行をグループ化
having(condition)DataStoreグループを絞り込み
join(right, ...)DataStoreDataStore を結合
union(other, all=False)DataStoreDataStore を結合(UNION)
when(cond, val)CaseWhenCASE WHEN

詳細は Query Building を参照してください。

Pandas 互換メソッド

全 209 個のメソッドの一覧は、Pandas 互換性 を参照してください。

インデックス操作: head(), tail(), sample(), loc, iloc, at, iat, query(), isin(), where(), mask(), get(), xs(), pop()

集約: sum(), mean(), std(), var(), min(), max(), median(), count(), nunique(), quantile(), describe(), corr(), cov(), skew(), kurt()

データ操作: drop(), drop_duplicates(), dropna(), fillna(), replace(), rename(), assign(), astype(), copy()

並べ替え: sort_values(), sort_index(), nlargest(), nsmallest(), rank()

再構成: pivot(), pivot_table(), melt(), stack(), unstack(), transpose(), explode(), squeeze()

結合: merge(), join(), concat(), append(), combine(), update(), compare()

適用/変換: apply(), applymap(), map(), agg(), transform(), pipe(), groupby()

時系列: rolling(), expanding(), ewm(), shift(), diff(), pct_change(), resample()

I/O メソッド

MethodDescription
to_csv(path, ...)CSV にエクスポート
to_parquet(path, ...)Parquet にエクスポート
to_json(path, ...)JSON にエクスポート
to_excel(path, ...)Excel にエクスポート
to_df()pandas DataFrame に変換
to_pandas()to_df のエイリアス
to_arrow()Arrow Table に変換
to_dict(orient)辞書に変換
to_records()レコードに変換
to_numpy()NumPy 配列に変換
to_sql()SQL 文字列を生成
to_string()文字列表現を生成
to_markdown()Markdown 形式のテーブルを生成
to_html()HTML 形式のテーブルを生成

詳細は I/O Operations を参照してください。

デバッグメソッド

メソッド説明
explain(verbose=False)実行計画を表示します
clear_cache()キャッシュされた結果をクリアします

詳しくは Debugging を参照してください。

マジックメソッド

メソッド説明
__getitem__(key)ds['col'], ds[['a', 'b']], ds[condition]
__setitem__(key, value)ds['col'] = value
__delitem__(key)del ds['col']
__len__()len(ds)
__iter__()for col in ds
__contains__(key)'col' in ds
__repr__()repr(ds)
__str__()str(ds)
__eq__(other)ds == other
__ne__(other)ds != other
__lt__(other)ds < other
__le__(other)ds <= other
__gt__(other)ds > other
__ge__(other)ds >= other
__add__(other)ds + other
__sub__(other)ds - other
__mul__(other)ds * other
__truediv__(other)ds / other
__floordiv__(other)ds // other
__mod__(other)ds % other
__pow__(other)ds ** other
__and__(other)ds & other
__or__(other)`ds
__invert__()~ds
__neg__()-ds
__pos__()+ds
__abs__()abs(ds)

ColumnExpr

遅延評価されるカラム式を表します。カラムにアクセスしたときに返されます。

# ColumnExpr is returned automatically
col = ds['name']  # Returns ColumnExpr

プロパティ

プロパティ説明
namestrカラム名
dtypedtypeデータ型

アクセサ

Accessor説明メソッド数
.str文字列操作56 メソッド
.dt日時操作42+ メソッド
.arr配列操作37 メソッド
.jsonJSON 解析13 メソッド
.urlURL 解析15 メソッド
.ipIP アドレス操作9 メソッド
.geo地理/距離操作14 メソッド

詳細は Accessors を参照してください。

算術演算

ds['total'] = ds['price'] * ds['quantity']
ds['profit'] = ds['revenue'] - ds['cost']
ds['ratio'] = ds['a'] / ds['b']
ds['squared'] = ds['value'] ** 2
ds['remainder'] = ds['value'] % 10

比較演算

ds[ds['age'] > 25]           # Greater than
ds[ds['age'] >= 25]          # Greater or equal
ds[ds['age'] < 25]           # Less than
ds[ds['age'] <= 25]          # Less or equal
ds[ds['name'] == 'Alice']    # Equal
ds[ds['name'] != 'Bob']      # Not equal

論理演算

ds[(ds['age'] > 25) & (ds['city'] == 'NYC')]    # AND
ds[(ds['age'] > 25) | (ds['city'] == 'NYC')]    # OR
ds[~(ds['status'] == 'inactive')]               # NOT

メソッド

MethodDescription
as_(alias)エイリアス名を設定
cast(dtype)指定した型にキャスト
astype(dtype)cast のエイリアス
isnull()NULL かどうか
notnull()NULL ではないかどうか
isna()isnull のエイリアス
notna()notnull のエイリアス
isin(values)値のリストに含まれるか
between(low, high)2 つの値の間かどうか
fillna(value)NULL を指定値で埋める
replace(to_replace, value)値を置換
clip(lower, upper)値を下限・上限でクリップ
abs()絶対値
round(decimals)値を丸める
floor()小さい方の整数への切り捨て
ceil()大きい方の整数への切り上げ
apply(func)関数を適用
map(mapper)値をマッピング

集約メソッド

Method説明
sum()合計
mean()平均
avg()mean の別名
min()最小値
max()最大値
count()null 以外の要素数
nunique()一意な要素数
std()標準偏差
var()分散
median()中央値
quantile(q)分位数
first()最初の値
last()最後の値
any()どれか 1 つでも true
all()すべてが true

LazyGroupBy

集約処理を行うためのグループ化済み DataStore を表します。

# LazyGroupBy is returned automatically
grouped = ds.groupby('category')  # Returns LazyGroupBy

メソッド

メソッド戻り値説明
agg(spec)DataStore集約
aggregate(spec)DataStoreagg のエイリアス
sum()DataStoreグループごとの合計
mean()DataStoreグループごとの平均
count()DataStoreグループごとの件数
min()DataStoreグループごとの最小値
max()DataStoreグループごとの最大値
std()DataStoreグループごとの標準偏差
var()DataStoreグループごとの分散
median()DataStoreグループごとの中央値
nunique()DataStoreグループごとのユニークな値の数
first()DataStoreグループごとの先頭値
last()DataStoreグループごとの末尾値
nth(n)DataStoreグループごとの n 番目の値
head(n)DataStoreグループごとの先頭 n 件
tail(n)DataStoreグループごとの末尾 n 件
apply(func)DataStoreグループごとに関数を適用
transform(func)DataStoreグループごとに変換
filter(func)DataStoreグループをフィルタリング

カラムの選択

# Select column after groupby
grouped['amount'].sum()     # Returns DataStore
grouped[['a', 'b']].sum()   # Returns DataStore

集約の仕様

# Single aggregation
grouped.agg({'amount': 'sum'})

# Multiple aggregations per column
grouped.agg({'amount': ['sum', 'mean', 'count']})

# Named aggregations
grouped.agg(
    total=('amount', 'sum'),
    average=('amount', 'mean'),
    count=('id', 'count')
)

LazySeries

遅延評価される Series(単一カラム)を表します。

プロパティ

プロパティ説明
namestrシリーズ名
dtypedtypeデータ型

メソッド

ほとんどのメソッドを ColumnExpr から継承します。主なメソッドは次のとおりです。

メソッド説明
value_counts()値の出現頻度
unique()一意な値
nunique()一意な値の数
mode()最頻値
to_list()list への変換
to_numpy()NumPy 配列への変換
to_frame()DataStore への変換

F(関数)

ClickHouse の関数用のネームスペース。

from chdb.datastore import F, Field

# Aggregations
F.sum(Field('amount'))
F.avg(Field('price'))
F.count(Field('id'))
F.quantile(Field('value'), 0.95)

# Conditional
F.sum_if(Field('amount'), Field('status') == 'completed')
F.count_if(Field('active'))

# Window
F.row_number().over(order_by='date')
F.lag('price', 1).over(partition_by='product', order_by='date')

詳しくは Aggregation を参照してください。

フィールド

カラム名による参照。

from chdb.datastore import Field

# Create field reference
amount = Field('amount')
price = Field('price')

# Use in expressions
F.sum(Field('amount'))
F.avg(Field('price'))

CaseWhen

CASE WHEN 式を構築するためのビルダー。

# Create case-when expression
result = (ds
    .when(ds['score'] >= 90, 'A')
    .when(ds['score'] >= 80, 'B')
    .when(ds['score'] >= 70, 'C')
    .otherwise('F')
)

# Assign to column
ds['grade'] = result

Window

ウィンドウ関数におけるウィンドウの指定。

from chdb.datastore import F

# Create window
window = F.window(
    partition_by='category',
    order_by='date',
    rows_between=(-7, 0)
)

# Use with aggregation
ds['rolling_avg'] = F.avg('price').over(window)