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

# Pandas 쿡북

> 일반적인 pandas 패턴과 이에 해당하는 DataStore 방식

일반적인 pandas 패턴과 이에 해당하는 DataStore 방식을 소개합니다. 대부분의 코드는 수정 없이 그대로 작동합니다!

<div id="loading">
  ## 데이터 로딩
</div>

<div id="read-csv">
  ### CSV 읽기
</div>

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

# DataStore - 동일합니다!
from chdb import datastore as pd
df = pd.read_csv("data.csv")
```

<div id="read-multiple-files">
  ### 여러 파일 읽기
</div>

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

# DataStore - glob pattern을 사용하면 더 효율적
df = pd.read_csv("data/*.csv")
```

***

<div id="filtering">
  ## 필터링
</div>

<div id="single-condition">
  ### 하나의 조건
</div>

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

<div id="multiple-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">
  ### query() 사용
</div>

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

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

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

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

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

***

<div id="selecting">
  ## 컬럼 선택
</div>

<div id="single-column-select">
  ### 단일 컬럼
</div>

```python theme={null}
# Pandas와 DataStore - 동일
df['name']
df.name  # 속성 접근
```

<div id="multiple-columns-select">
  ### 여러 컬럼
</div>

```python theme={null}
# Pandas와 DataStore - 동일
df[['name', 'age', 'city']]
```

<div id="select-and-filter">
  ### 선택 및 필터링
</div>

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

# DataStore는 SQL 스타일도 지원
df.filter(df['age'] > 25).select('name', 'salary')
```

***

<div id="sorting">
  ## 정렬
</div>

<div id="single-column-select">
  ### 단일 컬럼
</div>

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

<div id="multiple-columns-select">
  ### 여러 컬럼
</div>

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

<div id="get-top-bottom-n">
  ### 상위/하위 N개 가져오기
</div>

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

***

<div id="groupby">
  ## GroupBy 및 집계
</div>

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

```python theme={null}
# Pandas와 DataStore - 동일
df.groupby('city')['salary'].mean()
df.groupby('city')['salary'].sum()
df.groupby('city').size()  # 개수
```

<div id="multiple-aggregations">
  ### 다중 집계
</div>

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

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

<div id="named-aggregations">
  ### 명명된 집계
</div>

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

<div id="multiple-groupby-keys">
  ### 여러 GroupBy 키
</div>

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

***

<div id="joining">
  ## 데이터 조인하기
</div>

<div id="inner-join">
  ### 내부 조인
</div>

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

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

# DataStore에서도 지원
df1.join(df2, on='id')
```

<div id="left-join">
  ### LEFT JOIN
</div>

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

<div id="join-on-different-columns">
  ### 서로 다른 컬럼으로 조인
</div>

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

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

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

***

<div id="string">
  ## 문자열 연산
</div>

<div id="case-conversion">
  ### 대소문자 변환
</div>

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

<div id="substring">
  ### 부분 문자열
</div>

```python theme={null}
# Pandas와 DataStore - 동일
df['name'].str[:3]        # 처음 3개의 문자
df['name'].str.slice(0, 3)
```

<div id="search">
  ### 검색
</div>

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

<div id="replace">
  ### 치환
</div>

```python theme={null}
# Pandas와 DataStore - 동일
df['text'].str.replace('old', 'new')
df['text'].str.replace(r'\d+', '', regex=True)  # 숫자 제거
```

<div id="split">
  ### 분리
</div>

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

<div id="length">
  ### 길이
</div>

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

***

<div id="datetime">
  ## DateTime 연산
</div>

<div id="extract-components">
  ### 날짜/시간 요소 추출
</div>

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

<div id="formatting">
  ### 포맷팅
</div>

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

***

<div id="missing">
  ## 데이터 누락
</div>

<div id="check-missing">
  ### 결측값 확인
</div>

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

<div id="drop-missing">
  ### 결측값 제거
</div>

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

<div id="fill-missing">
  ### 누락값 채우기
</div>

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

***

<div id="new-columns">
  ## 새 컬럼 생성
</div>

<div id="simple-assignment">
  ### 단순 대입
</div>

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

<div id="using-assign">
  ### assign() 사용하기
</div>

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

<div id="conditional-where-mask">
  ### 조건식(where/mask)
</div>

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

<div id="apply-for-custom-logic">
  ### 사용자 지정 로직용 apply()
</div>

```python theme={null}
# 작동하지만 pandas 실행을 트리거함
df['category'] = df['amount'].apply(lambda x: 'high' if x > 1000 else 'low')

# DataStore 대안 (지연 실행 유지)
df['category'] = (
    df.when(df['amount'] > 1000, 'high')
      .otherwise('low')
)
```

***

<div id="reshaping">
  ## 형태 변환
</div>

<div id="pivot-table">
  ### 피벗 테이블
</div>

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

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

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

<div id="explode">
  ### 확장
</div>

```python theme={null}
# Pandas와 DataStore - 동일
df.explode('tags')  # 배열 컬럼 확장
```

***

<div id="window">
  ## 윈도우 함수
</div>

<div id="rolling">
  ### 롤링
</div>

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

<div id="expanding">
  ### 확장형
</div>

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

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

```python theme={null}
# Pandas와 DataStore - 동일
df['prev_value'] = df['value'].shift(1)   # 지연(Lag)
df['next_value'] = df['value'].shift(-1)  # 선행(Lead)
```

<div id="diff">
  ### 차이
</div>

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

***

<div id="output">
  ## 출력
</div>

<div id="to-csv">
  ### CSV로 출력
</div>

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

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

```python theme={null}
# Pandas와 DataStore - 동일
df.to_parquet("output.parquet")
```

<div id="to-pandas-dataframe">
  ### pandas DataFrame으로 변환
</div>

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

***

<div id="extras">
  ## DataStore 추가 기능
</div>

<div id="view-sql">
  ### SQL 보기
</div>

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

<div id="explain-plan">
  ### 실행 계획 설명
</div>

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

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

```python theme={null}
# DataStore 전용 - 추가 Accessor
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
</div>

```python theme={null}
# DataStore 전용 - 어디서든 읽기 가능
ds = DataStore.uri("s3://bucket/data.parquet")
ds = DataStore.uri("mysql://user:pass@host/db/table")
```
