use crate::error::Result;
use crate::value::{Array, Frame, Series, Value};
mod arrow;
mod blocks;
mod index;
use blocks::block_parts;
use index::{index_labels, index_values};
pub fn is_pandas(v: &Value) -> bool {
matches!(v, Value::Object(o) if o.module.starts_with("pandas"))
}
pub fn to_frame(v: &Value) -> Result<Option<Frame>> {
let o = match v {
Value::Object(o) if is_pandas(v) => o,
_ => return Ok(None),
};
let mgr = match o.state.as_deref() {
Some(Value::Dict(d)) => match d.get("_mgr").or_else(|| d.get("_data")) {
Some(m) => m,
None => return Ok(None),
},
Some(other) => other,
None => return Ok(None),
};
from_manager(mgr)
}
fn manager_parts(mgr: &Value) -> Option<(Vec<Value>, Vec<Value>)> {
let parts: Vec<Value> = match mgr {
Value::Object(o) if !o.args.is_empty() => o.args.clone(),
Value::Object(o) => match o.state.as_deref() {
Some(Value::Tuple(t)) | Some(Value::List(t)) => t.clone(),
Some(Value::Dict(d)) => vec![d.get("axes")?.clone(), d.get("blocks")?.clone()],
_ => return None,
},
Value::Tuple(t) | Value::List(t) => t.clone(),
_ => return None,
};
let seq = |v: &Value| match v {
Value::Tuple(t) | Value::List(t) => Some(t.clone()),
_ => None,
};
let (a, b) = (seq(parts.first()?)?, seq(parts.get(1)?)?);
if a.iter().any(is_index) {
Some((b, a))
} else {
Some((a, b))
}
}
fn is_index(v: &Value) -> bool {
matches!(v, Value::Object(o)
if o.name.contains("Index") || o.name == "_new_Index")
}
fn from_manager(mgr: &Value) -> Result<Option<Frame>> {
let (blocks, axes) = match manager_parts(mgr) {
Some(p) => p,
None => return Ok(None),
};
let names = index_labels(axes.first());
let row_index = axes.get(1).and_then(index_values);
let mut columns: Vec<Option<Series>> = vec![None; names.len()];
for block in &blocks {
let (values, placement) = match block_parts(block) {
Some(p) => p,
None => continue,
};
for (row, pos) in placement.iter().enumerate() {
let col = match split_row(&values, row, placement.len()) {
Some(c) => c,
None => continue,
};
if *pos >= columns.len() {
columns.resize(*pos + 1, None);
}
let name = names.get(*pos).cloned().unwrap_or_else(|| format!("column_{pos}"));
columns[*pos] = Some(Series::new(&name, col));
}
}
let cols: Vec<Series> = columns.into_iter().flatten().collect();
if cols.is_empty() {
return Ok(None);
}
let mut f = Frame::from_columns(cols)?;
f.index = row_index.map(|a| Series::new("index", a));
Ok(Some(f))
}
fn split_row(a: &Array, r: usize, count: usize) -> Option<Array> {
if a.ndim() == 1 {
return if count == 1 && r == 0 { Some(a.clone()) } else { None };
}
a.row(r)
}