Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-ops/src/chunked_array/cov.rs
6939 views
1
use num_traits::AsPrimitive;
2
use polars_compute::moment::{CovState, PearsonState};
3
use polars_core::prelude::*;
4
use polars_core::utils::align_chunks_binary;
5
6
/// Compute the covariance between two columns.
7
pub fn cov<T>(a: &ChunkedArray<T>, b: &ChunkedArray<T>, ddof: u8) -> Option<f64>
8
where
9
T: PolarsNumericType,
10
T::Native: AsPrimitive<f64>,
11
ChunkedArray<T>: ChunkVar,
12
{
13
let (a, b) = align_chunks_binary(a, b);
14
let mut out = CovState::default();
15
for (a, b) in a.downcast_iter().zip(b.downcast_iter()) {
16
out.combine(&polars_compute::moment::cov(a, b))
17
}
18
out.finalize(ddof)
19
}
20
21
/// Compute the pearson correlation between two columns.
22
pub fn pearson_corr<T>(a: &ChunkedArray<T>, b: &ChunkedArray<T>) -> Option<f64>
23
where
24
T: PolarsNumericType,
25
T::Native: AsPrimitive<f64>,
26
ChunkedArray<T>: ChunkVar,
27
{
28
let (a, b) = align_chunks_binary(a, b);
29
let mut out = PearsonState::default();
30
for (a, b) in a.downcast_iter().zip(b.downcast_iter()) {
31
out.combine(&polars_compute::moment::pearson_corr(a, b))
32
}
33
Some(out.finalize())
34
}
35
36