# Chalk DataFrames Reference: Creating DataFrames
source: https://docs.chalk.ai/dataframe-docs#section-creating-dataframes

Class methods for constructing new [`DataFrame`](https://docs.chalk.ai/dataframe-docs#DataFrame) instances from various sources.

- From Python dicts or Arrow tables in memory
- From Parquet, CSV, or Delta files on disk or cloud storage
- From AWS Glue Iceberg tables
- From Chalk SQL queries or external SQL data sources
- From streaming sources (Kafka, Kinesis, PubSub)
- From Chalk SQL catalog tables
- Schema-only placeholders via `named_table` (data injected at run time)

## `named_table(name, schema, sorted_by)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.named_table

Create a schema-only placeholder [`DataFrame`](https://docs.chalk.ai/dataframe-docs#DataFrame) for a named table.

The returned DataFrame contains _no data_; it is a logical reference that must be supplied with actual Arrow data at execution time via the `tables` argument of `run` or `to_arrow`. This is useful when you want to build a reusable query plan against a well-known schema and inject different data at runtime.

**Parameters**

- `name`: `str`
  Table identifier used as the key in the `tables` mapping at execution time.
- `schema`: `pyarrow.Schema`
  Arrow schema describing the table's columns and types.
- `sorted_by`: `list[str] | None` = `None`
  Optional list of column names indicating that the data is pre-sorted by those columns (used for optimisation hints).

**Returns**

`DataFrame`

**Examples**

```python
import pyarrow as pa
from chalkdf import DataFrame
schema = pa.schema([("user_id", pa.int64()), ("score", pa.float64())])
df = DataFrame.named_table("users", schema)
# Build a query plan
from chalk.features import _
result_plan = df.filter(_.score > 0.5)
# Inject real data at execution time
import pyarrow as pa
data = pa.table({"user_id": [1, 2, 3], "score": [0.3, 0.8, 0.6]})
result = result_plan.run(tables={"users": data})
```

## `from_dict(data)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_dict

Construct a DataFrame from a Python dictionary.

**Parameters**

- `data`: `dict`
  Dictionary mapping column names to lists of values.

**Returns**

**Examples**

```python
from chalkdf import DataFrame
df = DataFrame.from_dict({"x": [1, 2, 3], "y": ["a", "b", "c"]})
```

## `from_arrow(data)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_arrow

Construct a DataFrame from an in-memory Arrow object.

**Parameters**

- `data`: `MaterializedTable`
  PyArrow Table or RecordBatch to convert into a DataFrame.

**Returns**

**Examples**

```python
import pyarrow as pa
from chalkdf import DataFrame
table = pa.table({"x": [1, 2, 3], "y": ["a", "b", "c"]})
df = DataFrame.from_arrow(table)
```

## `scan(input_uris, name, schema, mode, row_sample)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.scan

Scan files and return a DataFrame.

Currently supports CSV (with headers), Parquet, Delta, and Iceberg.

**Parameters**

- `input_uris`: `Sequence[str | Path] | str | Path`
  File path/URI or list of paths/URIs to scan. Supports local paths and file:// URIs.
- `name`: `str | None` = `None`
  Optional name to assign to the table being scanned.
- `schema`: `pyarrow.Schema | None` = `None`
  Schema of the data. Required for CSV files, optional for Parquet. For Delta and Iceberg, inferred from table metadata when omitted.
- `mode`: `'auto' | 'hive' | 'delta' | 'iceberg'` = `'auto'`
  Scan inference mode:

  - `"auto"`: infer scan type from the URI/path. Uses suffixes for CSV/Parquet and can also recognize Delta table roots.
  - `"hive"`: expand Hive/glob paths without Delta inference fallback.
  - `"delta"`: treat the input as a Delta table root (requires exactly one URI).
  - `"iceberg"`: treat the input as an Iceberg table root (requires exactly one URI). To read from a catalog instead of file system, use `scan_iceberg`.
- `row_sample`: `float | None` = `None`
  Optional Bernoulli row-level sampling rate in (0, 1]. For example, `0.01` yields ~1% of rows. Passed through to the Velox Hive connector's `sampleRate`; sampling is non-uniform and skips rows during read (it does not skip files or row groups, so I/O is not reduced proportionally). [`None`](https://docs.python.org/3/library/constants.html#None) disables sampling.

**Returns**

`DataFrame`

**Examples**

```python
from chalkdf import DataFrame
# Scan Parquet files
df = DataFrame.scan(["data/sales_2024.parquet"], name="sales_data")
# Scan CSV with explicit schema
import pyarrow as pa
schema = pa.schema([("id", pa.int64()), ("name", pa.string())])
df = DataFrame.scan(["data/users.csv"], schema=schema)
# Scan ~1% of rows
df = DataFrame.scan(["data/big.parquet"], row_sample=0.01)
```

## `scan_glue_iceberg(glue_table_name, schema, batch_row_count, aws_catalog_account_id, aws_catalog_region, aws_role_arn, filter_predicate, parquet_scan_range_column, custom_partitions, partition_column)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.scan_glue_iceberg

Load data from an AWS Glue Iceberg table.

**Parameters**

- `glue_table_name`: `str`
  Fully qualified `database.table` name.
- `schema`: `Mapping[str, pyarrow.DataType]`
  Mapping of column names to Arrow types.
- `batch_row_count`: `int` = `1000`
  Number of rows per batch.
- `aws_catalog_account_id`: `str | None` = `None`
  AWS account hosting the Glue catalog.
- `aws_catalog_region`: `str | None` = `None`
  Region of the Glue catalog.
- `aws_role_arn`: `str | None` = `None`
  IAM role to assume for access.
- `filter_predicate`: `Expr | None` = `None`
  Optional filter applied during scan.
- `parquet_scan_range_column`: `str | None` = `None`
  Column used for range-based reads.
- `custom_partitions`: `dict[str, tuple['date_trunc(day)', str]] | None` = `None`
  Additional partition definitions.
- `partition_column`: `str | None` = `None`
  Column name representing partitions.

**Returns**

`DataFrame`

## `from_sql(query, tables)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_sql

Create a [`DataFrame`](https://docs.chalk.ai/dataframe-docs#DataFrame) from the result of executing a Chalk SQL query.

Pass DataFrames or Arrow tables as keyword arguments to make them available as named tables inside the query. If no keyword arguments are provided, `from_sql` will attempt to auto-register any DataFrames found in the calling scope.

**Parameters**

- `query`: `str`
  Chalk SQL query string.
- `tables`: `CompatibleFrameType` = `{}`

**Returns**

`DataFrame`

**Examples**

```python
from chalkdf import DataFrame
orders = DataFrame.from_dict({"order_id": [1, 2, 3], "amount": [10.0, 20.0, 5.0]})
result = DataFrame.from_sql(
    "SELECT order_id, amount FROM orders WHERE amount > 8",
    orders=orders,
)
```

Join two DataFrames with SQL:

```python
users = DataFrame.from_dict({"id": [1, 2], "name": ["Alice", "Bob"]})
purchases = DataFrame.from_dict({"user_id": [1, 1, 2], "item": ["a", "b", "c"]})
result = DataFrame.from_sql(
    "SELECT u.name, p.item FROM users u JOIN purchases p ON u.id = p.user_id",
    users=users,
    purchases=purchases,
)
```

## `from_stream_source(source, n, timeout_ms, include_metadata)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_stream_source

Create a DataFrame by pulling messages from a streaming source.

This method connects to a Kafka, Kinesis, or PubSub source and pulls up to `n` messages, returning them as a DataFrame.

**Parameters**

- `source`: `Any`
  A streaming source configuration. Can be one of:

  - `KafkaSource`: Kafka topic configuration
  - `KinesisSource`: Kinesis stream configuration
  - `PubSubSource`: Google PubSub subscription configuration
- `n`: `int`
  Maximum number of messages to pull from the stream.
- `timeout_ms`: `int` = `15000`
  Timeout in milliseconds for pulling messages. Default is 15000ms.
- `include_metadata`: `bool` = `False`
  If False (default), returns a DataFrame with a single "value" column containing the raw message bytes. If True, returns a DataFrame with columns for topic, partition, offset, timestamp, key, and value.

**Returns**

`DataFrame`

**Examples**

```python
from chalkdf import DataFrame
from chalk.streams import KafkaSource
source = KafkaSource(
    name="my_kafka",
    bootstrap_server="localhost:9092",
    topic="my_topic",
)
# Pull 100 messages, just the raw bytes
df = DataFrame.from_stream_source(source, n=100)
# Pull with full metadata
df = DataFrame.from_stream_source(source, n=100, include_metadata=True)
```

## `from_catalog_table(table_name, catalog)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_catalog_table

Create a DataFrame from a Chalk SQL catalog table.

**Parameters**

- `table_name`: `str`
  Name of the table in the catalog.
- `catalog`: `ChalkSqlCatalog`
  ChalkSqlCatalog instance containing the table.

**Returns**

`DataFrame`

**Examples**

```python
from chalkdf import DataFrame
from libchalk.chalksql import ChalkSqlCatalog
catalog = ChalkSqlCatalog()
df = DataFrame.from_catalog_table("users", catalog=catalog)
```

## `from_datasource(source, query, expected_output_schema)`
source: https://docs.chalk.ai/dataframe-docs#DataFrame.from_datasource

Create a DataFrame from the result of querying a SQL data source.

**Parameters**

- `source`: `BaseSQLSource`
  SQL source to query (e.g., PostgreSQL, Snowflake, BigQuery).
- `query`: `str`
  SQL query to execute against the data source.
- `expected_output_schema`: `pyarrow.Schema`
  Output schema of the query result. The datasource's driver converts the native query result to this schema.

**Returns**

**Examples**

```python
import pyarrow as pa
from chalkdf import DataFrame
from chalk.sql import PostgreSQLSource
source = PostgreSQLSource(...)
schema = pa.schema([("user_id", pa.int64()), ("name", pa.string())])
df = DataFrame.from_datasource(source, "SELECT * FROM users", schema)
```
