> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cookbook Pandas

> Cas d’usage pandas courants et leurs équivalents dans DataStore

Cas d’usage pandas courants et leurs équivalents dans DataStore. La plupart du code fonctionne sans modification !

<div id="loading">
  ## Chargement des données
</div>

<div id="read-csv">
  ### Lire un fichier CSV
</div>

```python theme={null}
# Pandas
import pandas as pd
df = pd.read_csv("data.csv")

# DataStore - same!
from chdb import datastore as pd
df = pd.read_csv("data.csv")
```

<div id="read-multiple-files">
  ### Lire plusieurs fichiers
</div>

```python theme={null}
# Pandas
import glob
dfs = [pd.read_csv(f) for f in glob.glob("data/*.csv")]
df = pd.concat(dfs)

# DataStore - more efficient with glob pattern
df = pd.read_csv("data/*.csv")
```

***

<div id="filtering">
  ## Filtrage
</div>

<div id="single-condition">
  ### Condition unique
</div>

```python theme={null}
# Pandas and DataStore - identical
df[df['age'] > 25]
df[df['city'] == 'NYC']
df[df['name'].str.contains('John')]
```

<div id="multiple-conditions">
  ### Plusieurs conditions
</div>

```python theme={null}
# AND
df[(df['age'] > 25) & (df['city'] == 'NYC')]

# OR
df[(df['age'] < 18) | (df['age'] > 65)]

# NOT
df[~(df['status'] == 'inactive')]
```

<div id="using-query">
  ### Utiliser query()
</div>

```python theme={null}
# Pandas and DataStore - identical
df.query('age > 25 and city == "NYC"')
df.query('salary > 50000')
```

<div id="isin">
  ### isin()
</div>

```python theme={null}
# Pandas and DataStore - identical
df[df['city'].isin(['NYC', 'LA', 'SF'])]
```

<div id="between">
  ### between()
</div>

```python theme={null}
# Pandas and DataStore - identical
df[df['age'].between(18, 65)]
```

***

<div id="selecting">
  ## Sélection des colonnes
</div>

<div id="single-column-select">
  ### Une seule colonne
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name']
df.name  # attribute access
```

<div id="multiple-columns-select">
  ### Plusieurs colonnes
</div>

```python theme={null}
# Pandas and DataStore - identical
df[['name', 'age', 'city']]
```

<div id="select-and-filter">
  ### Sélection et filtrage
</div>

```python theme={null}
# Pandas and DataStore - identical
df[df['age'] > 25][['name', 'salary']]

# DataStore also supports SQL-style
df.filter(df['age'] > 25).select('name', 'salary')
```

***

<div id="sorting">
  ## Tri
</div>

<div id="single-column-select">
  ### Une seule colonne
</div>

```python theme={null}
# Pandas and DataStore - identical
df.sort_values('salary')
df.sort_values('salary', ascending=False)
```

<div id="multiple-columns-select">
  ### Plusieurs colonnes
</div>

```python theme={null}
# Pandas and DataStore - identical
df.sort_values(['city', 'salary'], ascending=[True, False])
```

<div id="get-top-bottom-n">
  ### Obtenir les N valeurs les plus élevées/les plus faibles
</div>

```python theme={null}
# Pandas and DataStore - identical
df.nlargest(10, 'salary')
df.nsmallest(5, 'age')
```

***

<div id="groupby">
  ## GroupBy et agrégation
</div>

<div id="simple-groupby">
  ### GroupBy simple
</div>

```python theme={null}
# Pandas and DataStore - identical
df.groupby('city')['salary'].mean()
df.groupby('city')['salary'].sum()
df.groupby('city').size()  # count
```

<div id="multiple-aggregations">
  ### Agrégations multiples
</div>

```python theme={null}
# Pandas and DataStore - identical
df.groupby('city')['salary'].agg(['sum', 'mean', 'count'])

df.groupby('city').agg({
    'salary': ['sum', 'mean'],
    'age': ['min', 'max']
})
```

<div id="named-aggregations">
  ### Agrégations nommées
</div>

```python theme={null}
# Pandas and DataStore - identical
df.groupby('city').agg(
    total_salary=('salary', 'sum'),
    avg_salary=('salary', 'mean'),
    employee_count=('id', 'count')
)
```

<div id="multiple-groupby-keys">
  ### Plusieurs clés de GroupBy
</div>

```python theme={null}
# Pandas and DataStore - identical
df.groupby(['city', 'department'])['salary'].mean()
```

***

<div id="joining">
  ## Jointure de données
</div>

<div id="inner-join">
  ### Jointure interne
</div>

```python theme={null}
# Pandas
pd.merge(df1, df2, on='id')

# DataStore - same API
pd.merge(df1, df2, on='id')

# DataStore also supports
df1.join(df2, on='id')
```

<div id="left-join">
  ### Jointure gauche
</div>

```python theme={null}
# Pandas and DataStore - identical
pd.merge(df1, df2, on='id', how='left')
```

<div id="join-on-different-columns">
  ### Jointure sur des colonnes différentes
</div>

```python theme={null}
# Pandas and DataStore - identical
pd.merge(df1, df2, left_on='emp_id', right_on='id')
```

<div id="concat">
  ### Concat
</div>

```python theme={null}
# Pandas and DataStore - identical
pd.concat([df1, df2, df3])
pd.concat([df1, df2], axis=1)
```

***

<div id="string">
  ## Opérations sur les chaînes de caractères
</div>

<div id="case-conversion">
  ### Conversion de casse
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name'].str.upper()
df['name'].str.lower()
df['name'].str.title()
```

<div id="substring">
  ### Sous-chaîne
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name'].str[:3]        # First 3 characters
df['name'].str.slice(0, 3)
```

<div id="search">
  ### Search
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name'].str.contains('John')
df['name'].str.startswith('A')
df['name'].str.endswith('son')
```

<div id="replace">
  ### Replace
</div>

```python theme={null}
# Pandas and DataStore - identical
df['text'].str.replace('old', 'new')
df['text'].str.replace(r'\d+', '', regex=True)  # Remove digits
```

<div id="split">
  ### Séparation
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name'].str.split(' ')
df['name'].str.split(' ', expand=True)
```

<div id="length">
  ### Durée
</div>

```python theme={null}
# Pandas and DataStore - identical
df['name'].str.len()
```

***

<div id="datetime">
  ## Opérations sur DateTime
</div>

<div id="extract-components">
  ### Extraire les composants
</div>

```python theme={null}
# Pandas and DataStore - identical
df['date'].dt.year
df['date'].dt.month
df['date'].dt.day
df['date'].dt.dayofweek
df['date'].dt.hour
```

<div id="formatting">
  ### Formatage
</div>

```python theme={null}
# Pandas and DataStore - identical
df['date'].dt.strftime('%Y-%m-%d')
```

***

<div id="missing">
  ## Données manquantes
</div>

<div id="check-missing">
  ### Vérifier les valeurs manquantes
</div>

```python theme={null}
# Pandas and DataStore - identical
df['col'].isna()
df['col'].notna()
df.isna().sum()
```

<div id="drop-missing">
  ### Supprimer les valeurs manquantes
</div>

```python theme={null}
# Pandas and DataStore - identical
df.dropna()
df.dropna(subset=['col1', 'col2'])
```

<div id="fill-missing">
  ### Remplir les valeurs manquantes
</div>

```python theme={null}
# Pandas and DataStore - identical
df.fillna(0)
df.fillna({'col1': 0, 'col2': 'Unknown'})
df.fillna(method='ffill')
```

***

<div id="new-columns">
  ## Créer de nouvelles colonnes
</div>

<div id="simple-assignment">
  ### Affectation simple
</div>

```python theme={null}
# Pandas and DataStore - identical
df['total'] = df['price'] * df['quantity']
df['age_group'] = df['age'] // 10 * 10
```

<div id="using-assign">
  ### Utiliser assign()
</div>

```python theme={null}
# Pandas and DataStore - identical
df = df.assign(
    total=df['price'] * df['quantity'],
    is_adult=df['age'] >= 18
)
```

<div id="conditional-where-mask">
  ### Logique conditionnelle (where/mask)
</div>

```python theme={null}
# Pandas and DataStore - identical
df['status'] = df['age'].where(df['age'] >= 18, 'minor')
```

<div id="apply-for-custom-logic">
  ### apply() pour une logique personnalisée
</div>

```python theme={null}
# Works, but triggers pandas execution
df['category'] = df['amount'].apply(lambda x: 'high' if x > 1000 else 'low')

# DataStore alternative (stays lazy)
df['category'] = (
    df.when(df['amount'] > 1000, 'high')
      .otherwise('low')
)
```

***

<div id="reshaping">
  ## Mise en forme
</div>

<div id="pivot-table">
  ### Tableau croisé dynamique
</div>

```python theme={null}
# Pandas and DataStore - identical
df.pivot_table(
    values='amount',
    index='region',
    columns='product',
    aggfunc='sum'
)
```

<div id="melt-unpivot">
  ### Melt (unpivot)
</div>

```python theme={null}
# Pandas and DataStore - identical
df.melt(
    id_vars=['name'],
    value_vars=['score1', 'score2', 'score3'],
    var_name='test',
    value_name='score'
)
```

<div id="explode">
  ### Explode
</div>

```python theme={null}
# Pandas and DataStore - identical
df.explode('tags')  # Expand array column
```

***

<div id="window">
  ## Fonctions de fenêtre
</div>

<div id="rolling">
  ### Glissante
</div>

```python theme={null}
# Pandas and DataStore - identical
df['rolling_avg'] = df['price'].rolling(window=7).mean()
df['rolling_sum'] = df['amount'].rolling(window=30).sum()
```

<div id="expanding">
  ### Expansion
</div>

```python theme={null}
# Pandas and DataStore - identical
df['cumsum'] = df['amount'].expanding().sum()
df['cummax'] = df['amount'].expanding().max()
```

<div id="shift">
  ### Shift
</div>

```python theme={null}
# Pandas and DataStore - identical
df['prev_value'] = df['value'].shift(1)   # Lag
df['next_value'] = df['value'].shift(-1)  # Lead
```

<div id="diff">
  ### Diff
</div>

```python theme={null}
# Pandas and DataStore - identical
df['change'] = df['value'].diff()
df['pct_change'] = df['value'].pct_change()
```

***

<div id="output">
  ## Sortie
</div>

<div id="to-csv">
  ### En CSV
</div>

```python theme={null}
# Pandas and DataStore - identical
df.to_csv("output.csv", index=False)
```

<div id="to-parquet">
  ### Au format Parquet
</div>

```python theme={null}
# Pandas and DataStore - identical
df.to_parquet("output.parquet")
```

<div id="to-pandas-dataframe">
  ### Au format pandas DataFrame
</div>

```python theme={null}
# DataStore specific
pandas_df = ds.to_df()
pandas_df = ds.to_pandas()
```

***

<div id="extras">
  ## Suppléments de DataStore
</div>

<div id="view-sql">
  ### Afficher le SQL
</div>

```python theme={null}
# DataStore only
print(ds.to_sql())
```

<div id="explain-plan">
  ### Plan d’exécution
</div>

```python theme={null}
# DataStore only
ds.explain()
```

<div id="clickhouse-functions">
  ### Fonctions ClickHouse
</div>

```python theme={null}
# DataStore only - extra accessors
df['domain'] = df['url'].url.domain()
df['json_value'] = df['data'].json.get_string('key')
df['ip_valid'] = df['ip'].ip.is_ipv4_string()
```

<div id="universal-uri">
  ### URI universelle
</div>

```python theme={null}
# DataStore only - read from anywhere
ds = DataStore.uri("s3://bucket/data.parquet")
ds = DataStore.uri("mysql://user:pass@host/db/table")
```
