> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-detect-table-modification.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Pandas cookbook

> Common pandas patterns and their DataStore equivalents

Common pandas patterns and their DataStore equivalents. Most code works unchanged!

<h2 id="loading">
  Data Loading
</h2>

<h3 id="read-csv">
  Read CSV
</h3>

```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")
```

<h3 id="read-multiple-files">
  Read Multiple Files
</h3>

```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")
```

***

<h2 id="filtering">
  Filtering
</h2>

<h3 id="single-condition">
  Single Condition
</h3>

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

<h3 id="multiple-conditions">
  Multiple Conditions
</h3>

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

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

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

<h3 id="using-query">
  Using query()
</h3>

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

<h3 id="isin">
  isin()
</h3>

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

<h3 id="between">
  between()
</h3>

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

***

<h2 id="selecting">
  Selecting Columns
</h2>

<h3 id="single-column-select">
  Single Column
</h3>

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

<h3 id="multiple-columns-select">
  Multiple Columns
</h3>

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

<h3 id="select-and-filter">
  Select and Filter
</h3>

```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')
```

***

<h2 id="sorting">
  Sorting
</h2>

<h3 id="single-column-sort">
  Single Column
</h3>

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

<h3 id="multiple-columns-sort">
  Multiple Columns
</h3>

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

<h3 id="get-top-bottom-n">
  Get Top/Bottom N
</h3>

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

***

<h2 id="groupby">
  GroupBy and Aggregation
</h2>

<h3 id="simple-groupby">
  Simple GroupBy
</h3>

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

<h3 id="multiple-aggregations">
  Multiple Aggregations
</h3>

```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']
})
```

<h3 id="named-aggregations">
  Named Aggregations
</h3>

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

<h3 id="multiple-groupby-keys">
  Multiple GroupBy Keys
</h3>

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

***

<h2 id="joining">
  Joining Data
</h2>

<h3 id="inner-join">
  Inner Join
</h3>

```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')
```

<h3 id="left-join">
  Left Join
</h3>

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

<h3 id="join-on-different-columns">
  Join on Different Columns
</h3>

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

<h3 id="concat">
  Concat
</h3>

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

***

<h2 id="string">
  String Operations
</h2>

<h3 id="case-conversion">
  Case Conversion
</h3>

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

<h3 id="substring">
  Substring
</h3>

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

<h3 id="search">
  Search
</h3>

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

<h3 id="replace">
  Replace
</h3>

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

<h3 id="split">
  Split
</h3>

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

<h3 id="length">
  Length
</h3>

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

***

<h2 id="datetime">
  DateTime Operations
</h2>

<h3 id="extract-components">
  Extract Components
</h3>

```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
```

<h3 id="formatting">
  Formatting
</h3>

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

***

<h2 id="missing">
  Missing Data
</h2>

<h3 id="check-missing">
  Check Missing
</h3>

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

<h3 id="drop-missing">
  Drop Missing
</h3>

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

<h3 id="fill-missing">
  Fill Missing
</h3>

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

***

<h2 id="new-columns">
  Creating New Columns
</h2>

<h3 id="simple-assignment">
  Simple Assignment
</h3>

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

<h3 id="using-assign">
  Using assign()
</h3>

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

<h3 id="conditional-where-mask">
  Conditional (where/mask)
</h3>

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

<h3 id="apply-for-custom-logic">
  apply() for Custom Logic
</h3>

```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')
)
```

***

<h2 id="reshaping">
  Reshaping
</h2>

<h3 id="pivot-table">
  Pivot Table
</h3>

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

<h3 id="melt-unpivot">
  Melt (Unpivot)
</h3>

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

<h3 id="explode">
  Explode
</h3>

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

***

<h2 id="window">
  Window Functions
</h2>

<h3 id="rolling">
  Rolling
</h3>

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

<h3 id="expanding">
  Expanding
</h3>

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

<h3 id="shift">
  Shift
</h3>

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

<h3 id="diff">
  Diff
</h3>

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

***

<h2 id="output">
  Output
</h2>

<h3 id="to-csv">
  To CSV
</h3>

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

<h3 id="to-parquet">
  To Parquet
</h3>

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

<h3 id="to-pandas-dataframe">
  To pandas DataFrame
</h3>

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

***

<h2 id="extras">
  DataStore Extras
</h2>

<h3 id="view-sql">
  View SQL
</h3>

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

<h3 id="explain-plan">
  Explain Plan
</h3>

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

<h3 id="clickhouse-functions">
  ClickHouse Functions
</h3>

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

<h3 id="universal-uri">
  Universal URI
</h3>

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