Skip to content
ClickHouse Docs
ClickHouse DocsClickHouse Docs

مرجع صنف DataStore

يوثّق هذا المرجع الأصناف الأساسية ضمن واجهة برمجة تطبيقات DataStore.

DataStore

الصنف الأساسية الشبيهة بـ DataFrame لمعالجة البيانات.

from chdb.datastore import DataStore

المُنشئ

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

المعلمات:

المعلمة النوع الوصف
data dict/list/DataFrame/DataStore بيانات الإدخال
columns list أسماء الأعمدة
index Index فهرس الصف
dtype dict أنواع بيانات الأعمدة
copy bool نسخ البيانات

أمثلة:

# 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()

الخصائص

الخاصية النوع الوصف
columns Index أسماء الأعمدة
dtypes Series أنواع بيانات الأعمدة
shape tuple (الصفوف، الأعمدة)
size int إجمالي العناصر
ndim int عدد الأبعاد (2)
empty bool ما إذا كان DataFrame فارغًا
values ndarray البيانات الأساسية على هيئة مصفوفة NumPy
index Index فهرس الصفوف
T DataStore منقول
axes list قائمة المحاور

دوال المصنع

الطريقة الوصف
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

راجع دوال المصنع لمزيد من التفاصيل.

طرق الاستعلام

الطريقة القيمة المُعادة الوصف
select(*cols) DataStore تحديد الأعمدة
filter(condition) DataStore تصفية الصفوف
where(condition) DataStore اسم بديل لـ filter
sort(*cols, ascending=True) DataStore فرز الصفوف
orderby(*cols) DataStore اسم بديل لـ sort
limit(n) DataStore تقييد عدد الصفوف
offset(n) DataStore تخطي الصفوف
distinct(subset=None) DataStore إزالة التكرارات
groupby(*cols) LazyGroupBy تجميع الصفوف
having(condition) DataStore تصفية المجموعات
join(right, ...) DataStore ربط كائنات DataStore
union(other, all=False) DataStore دمج كائنات DataStore
when(cond, val) CaseWhen CASE WHEN

راجع بناء الاستعلامات لمزيد من التفاصيل.

الأساليب المتوافقة مع Pandas

راجع التوافق مع Pandas للاطّلاع على القائمة الكاملة التي تضم 209 أساليب.

الفهرسة: 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()

طرق الإدخال والإخراج

الطريقة الوصف
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

راجع عمليات الإدخال والإخراج للتفاصيل.

طرق تصحيح الأخطاء

الطريقة الوصف
explain(verbose=False) عرض خطة التنفيذ
clear_cache() مسح النتائج المخزنة مؤقتًا

راجع تصحيح الأخطاء لمزيد من التفاصيل.

الطرائق السحرية

الطريقة الوصف
__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 other`
__invert__() ~ds
__neg__() -ds
__pos__() +ds
__abs__() abs(ds)

ColumnExpr

يمثّل تعبيرًا لعمود يُستخدم في التقييم الكسول. ويُعاد عند الوصول إلى عمود.

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

الخصائص

الخاصية النوع الوصف
name str اسم العمود
dtype dtype نوع البيانات

أدوات الوصول

أداة الوصول الوصف الطرق
.str عمليات السلاسل النصية 56 طريقة
.dt عمليات DateTime 42+ طريقة
.arr عمليات Array 37 طريقة
.json تحليل JSON 13 طريقة
.url تحليل URL 15 طريقة
.ip عمليات عناوين IP 9 طريقة
.geo عمليات Geo وقياس المسافة 14 طريقة

راجع أدوات الوصول للاطلاع على الوثائق الكاملة.

العمليات الحسابية

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

الطرائق

الطريقة الوصف
as_(alias) تعيين اسم مستعار
cast(dtype) التحويل إلى نوع بيانات
astype(dtype) اسم مستعار لـ cast
isnull() NULL
notnull() ليس NULL
isna() اسم مستعار لـ isnull
notna() اسم مستعار لـ notnull
isin(values) ضمن قائمة قيم
between(low, high) بين قيمتين
fillna(value) ملء قيم NULL
replace(to_replace, value) استبدال القيم
clip(lower, upper) قصّ القيم
abs() القيمة المطلقة
round(decimals) تقريب القيم
floor() تقريب لأسفل
ceil() تقريب لأعلى
apply(func) تطبيق دالة
map(mapper) تحويل القيم

أساليب التجميع

الطريقة الوصف
sum() المجموع
mean() المتوسط
avg() اسم مستعار لـ mean
min() الحد الأدنى
max() الحد الأقصى
count() عدد القيم غير NULL
nunique() عدد القيم الفريدة
std() الانحراف المعياري
var() التباين
median() الوسيط
quantile(q) الكوانتايل
first() أول قيمة
last() آخر قيمة
any() أي قيمة تساوي true
all() جميع القيم تساوي true

LazyGroupBy

يمثل DataStore مُجمَّعًا يُستخدم لعمليات التجميع.

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

الأساليب

الأسلوب النتيجة الوصف
agg(spec) DataStore تجميع
aggregate(spec) DataStore اسم بديل لـ agg
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 بتقييم كسول (عمود واحد).

الخصائص

الخاصية النوع الوصف
name str اسم السلسلة
dtype dtype نوع البيانات

الطرق

ترث معظم الطرق من ColumnExpr. أهم الطرق:

الطريقة الوصف
value_counts() تكرارات القيم
unique() القيم الفريدة
nunique() عدد القيم الفريدة
mode() قيمة المنوال
to_list() تحويل إلى قائمة
to_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')

راجع التجميع لمزيد من التفاصيل.

الحقل

إشارة إلى عمود باسمه.

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

مواصفة 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)
Navigation