Trait polars_core::chunked_array::ops::ChunkVar
source · pub trait ChunkVar<T> {
fn var(&self, _ddof: u8) -> Option<T> { ... }
fn std(&self, _ddof: u8) -> Option<T> { ... }
}Expand description
Variance and standard deviation aggregation.
Provided Methods§
sourcefn var(&self, _ddof: u8) -> Option<T>
fn var(&self, _ddof: u8) -> Option<T>
Compute the variance of this ChunkedArray/Series.
Examples found in repository?
src/chunked_array/ops/aggregate.rs (line 477)
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
fn std(&self, ddof: u8) -> Option<f64> {
self.var(ddof).map(|var| var.sqrt())
}
}
impl ChunkVar<f32> for Float32Chunked {
fn var(&self, ddof: u8) -> Option<f32> {
if self.len() == 1 {
return Some(0.0);
}
let n_values = self.len() - self.null_count();
if ddof as usize > n_values {
return None;
}
let n_values = n_values as f32;
let mean = self.mean()? as f32;
let squared = self.apply(|value| {
let tmp = value - mean;
tmp * tmp
});
squared.sum().map(|sum| sum / (n_values - ddof as f32))
}
fn std(&self, ddof: u8) -> Option<f32> {
self.var(ddof).map(|var| var.sqrt())
}
}
impl ChunkVar<f64> for Float64Chunked {
fn var(&self, ddof: u8) -> Option<f64> {
if self.len() == 1 {
return Some(0.0);
}
let n_values = self.len() - self.null_count();
if ddof as usize > n_values {
return None;
}
let n_values = n_values as f64;
let mean = self.mean()?;
let squared = self.apply(|value| {
let tmp = value - mean;
tmp * tmp
});
squared.sum().map(|sum| sum / (n_values - ddof as f64))
}
fn std(&self, ddof: u8) -> Option<f64> {
self.var(ddof).map(|var| var.sqrt())
}More examples
src/frame/groupby/aggregations/mod.rs (line 808)
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
pub(crate) unsafe fn agg_var(&self, groups: &GroupsProxy, ddof: u8) -> Series {
let ca = &self.0;
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.var_as_series(ddof).unpack::<T>().unwrap().get(0)
}),
GroupsProxy::Slice { groups, .. } => {
if _use_rolling_kernels(groups, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => _rolling_apply_agg_window_no_nulls::<VarWindow<_>, _, _>(
values,
offset_iter,
),
Some(validity) => _rolling_apply_agg_window_nulls::<
rolling::nulls::VarWindow<_>,
_,
_,
>(values, validity, offset_iter),
};
ChunkedArray::<T>::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.var(ddof).map(|flt| NumCast::from(flt).unwrap())
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_std(&self, groups: &GroupsProxy, ddof: u8) -> Series {
let ca = &self.0;
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.std_as_series(ddof).unpack::<T>().unwrap().get(0)
}),
GroupsProxy::Slice { groups, .. } => {
if _use_rolling_kernels(groups, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => _rolling_apply_agg_window_no_nulls::<StdWindow<_>, _, _>(
values,
offset_iter,
),
Some(validity) => _rolling_apply_agg_window_nulls::<
rolling::nulls::StdWindow<_>,
_,
_,
>(values, validity, offset_iter),
};
ChunkedArray::<T>::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.std(ddof).map(|flt| NumCast::from(flt).unwrap())
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_quantile(
&self,
groups: &GroupsProxy,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> Series {
let ca = &self.0;
let invalid_quantile = !(0.0..=1.0).contains(&quantile);
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() | invalid_quantile {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.quantile_as_series(quantile, interpol)
.unwrap() // checked with invalid quantile check
.unpack::<T>()
.unwrap()
.get(0)
}),
GroupsProxy::Slice { groups, .. } => {
if _use_rolling_kernels(groups, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => rolling::no_nulls::rolling_quantile_by_iter(
values,
quantile,
interpol,
offset_iter,
),
Some(validity) => rolling::nulls::rolling_quantile_by_iter(
values,
validity,
quantile,
interpol,
offset_iter,
),
};
ChunkedArray::<T>::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
// unwrap checked with invalid quantile check
arr_group
.quantile(quantile, interpol)
.unwrap()
.map(|flt| NumCast::from(flt).unwrap())
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_median(&self, groups: &GroupsProxy) -> Series {
let ca = &self.0;
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.median_as_series().unpack::<T>().unwrap().get(0)
}),
GroupsProxy::Slice { .. } => {
self.agg_quantile(groups, 0.5, QuantileInterpolOptions::Linear)
}
}
}
}
impl<T> ChunkedArray<T>
where
T: PolarsIntegerType,
ChunkedArray<T>: IntoSeries,
T::Native: NumericNative + Ord,
<T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd>
+ arrow::compute::aggregate::Sum<T::Native>
+ arrow::compute::aggregate::SimdOrd<T::Native>,
{
pub(crate) unsafe fn agg_mean(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
_agg_helper_idx::<Float64Type, _>(groups, |(first, idx)| {
// this can fail due to a bug in lazy code.
// here users can create filters in aggregations
// and thereby creating shorter columns than the original group tuples.
// the group tuples are modified, but if that's done incorrect there can be out of bounds
// access
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize).map(|sum| sum.to_f64().unwrap())
} else {
match (self.has_validity(), self.chunks.len()) {
(false, 1) => {
take_agg_no_null_primitive_iter_unchecked(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
|a, b| a + b,
0.0f64,
)
}
.to_f64()
.map(|sum| sum / idx.len() as f64),
(_, 1) => {
{
take_agg_primitive_iter_unchecked_count_nulls::<
T::Native,
f64,
_,
_,
>(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
|a, b| a + b,
0.0,
idx.len() as IdxSize,
)
}
.map(|(sum, null_count)| {
sum / (idx.len() as f64 - null_count as f64)
})
}
_ => {
let take = { self.take_unchecked(idx.into()) };
take.mean()
}
}
}
})
}
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let ca = self.cast(&DataType::Float64).unwrap();
ca.agg_mean(groups)
} else {
_agg_helper_slice::<Float64Type, _>(groups_slice, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.mean()
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_var(&self, groups: &GroupsProxy, ddof: u8) -> Series {
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
return None;
}
let take = { self.take_unchecked(idx.into()) };
take.var_as_series(ddof)
.unpack::<Float64Type>()
.unwrap()
.get(0)
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let ca = self.cast(&DataType::Float64).unwrap();
ca.agg_var(groups, ddof)
} else {
_agg_helper_slice::<Float64Type, _>(groups_slice, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.var(ddof)
}
}
})
}
}
}
}sourcefn std(&self, _ddof: u8) -> Option<T>
fn std(&self, _ddof: u8) -> Option<T>
Compute the standard deviation of this ChunkedArray/Series.
Examples found in repository?
src/functions.rs (line 77)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
pub fn pearson_corr_i<T>(a: &ChunkedArray<T>, b: &ChunkedArray<T>, ddof: u8) -> Option<f64>
where
T: PolarsIntegerType,
T::Native: ToPrimitive,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: ChunkVar<f64>,
{
let (a, b) = coalesce_nulls(a, b);
let a = a.as_ref();
let b = b.as_ref();
Some(cov_i(a, b)? / (a.std(ddof)? * b.std(ddof)?))
}
/// Compute the pearson correlation between two columns.
pub fn pearson_corr_f<T>(a: &ChunkedArray<T>, b: &ChunkedArray<T>, ddof: u8) -> Option<T::Native>
where
T: PolarsFloatType,
T::Native: Float,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: ChunkVar<T::Native>,
{
let (a, b) = coalesce_nulls(a, b);
let a = a.as_ref();
let b = b.as_ref();
Some(cov_f(a, b)? / (a.std(ddof)? * b.std(ddof)?))
}More examples
src/frame/groupby/aggregations/mod.rs (line 852)
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
pub(crate) unsafe fn agg_std(&self, groups: &GroupsProxy, ddof: u8) -> Series {
let ca = &self.0;
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.std_as_series(ddof).unpack::<T>().unwrap().get(0)
}),
GroupsProxy::Slice { groups, .. } => {
if _use_rolling_kernels(groups, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => _rolling_apply_agg_window_no_nulls::<StdWindow<_>, _, _>(
values,
offset_iter,
),
Some(validity) => _rolling_apply_agg_window_nulls::<
rolling::nulls::StdWindow<_>,
_,
_,
>(values, validity, offset_iter),
};
ChunkedArray::<T>::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.std(ddof).map(|flt| NumCast::from(flt).unwrap())
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_quantile(
&self,
groups: &GroupsProxy,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> Series {
let ca = &self.0;
let invalid_quantile = !(0.0..=1.0).contains(&quantile);
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() | invalid_quantile {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.quantile_as_series(quantile, interpol)
.unwrap() // checked with invalid quantile check
.unpack::<T>()
.unwrap()
.get(0)
}),
GroupsProxy::Slice { groups, .. } => {
if _use_rolling_kernels(groups, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => rolling::no_nulls::rolling_quantile_by_iter(
values,
quantile,
interpol,
offset_iter,
),
Some(validity) => rolling::nulls::rolling_quantile_by_iter(
values,
validity,
quantile,
interpol,
offset_iter,
),
};
ChunkedArray::<T>::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
// unwrap checked with invalid quantile check
arr_group
.quantile(quantile, interpol)
.unwrap()
.map(|flt| NumCast::from(flt).unwrap())
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_median(&self, groups: &GroupsProxy) -> Series {
let ca = &self.0;
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<T, _>(groups, |idx| {
debug_assert!(idx.len() <= ca.len());
if idx.is_empty() {
return None;
}
let take = { ca.take_unchecked(idx.into()) };
take.median_as_series().unpack::<T>().unwrap().get(0)
}),
GroupsProxy::Slice { .. } => {
self.agg_quantile(groups, 0.5, QuantileInterpolOptions::Linear)
}
}
}
}
impl<T> ChunkedArray<T>
where
T: PolarsIntegerType,
ChunkedArray<T>: IntoSeries,
T::Native: NumericNative + Ord,
<T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd>
+ arrow::compute::aggregate::Sum<T::Native>
+ arrow::compute::aggregate::SimdOrd<T::Native>,
{
pub(crate) unsafe fn agg_mean(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
_agg_helper_idx::<Float64Type, _>(groups, |(first, idx)| {
// this can fail due to a bug in lazy code.
// here users can create filters in aggregations
// and thereby creating shorter columns than the original group tuples.
// the group tuples are modified, but if that's done incorrect there can be out of bounds
// access
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize).map(|sum| sum.to_f64().unwrap())
} else {
match (self.has_validity(), self.chunks.len()) {
(false, 1) => {
take_agg_no_null_primitive_iter_unchecked(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
|a, b| a + b,
0.0f64,
)
}
.to_f64()
.map(|sum| sum / idx.len() as f64),
(_, 1) => {
{
take_agg_primitive_iter_unchecked_count_nulls::<
T::Native,
f64,
_,
_,
>(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
|a, b| a + b,
0.0,
idx.len() as IdxSize,
)
}
.map(|(sum, null_count)| {
sum / (idx.len() as f64 - null_count as f64)
})
}
_ => {
let take = { self.take_unchecked(idx.into()) };
take.mean()
}
}
}
})
}
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let ca = self.cast(&DataType::Float64).unwrap();
ca.agg_mean(groups)
} else {
_agg_helper_slice::<Float64Type, _>(groups_slice, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize).map(|v| NumCast::from(v).unwrap()),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.mean()
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_var(&self, groups: &GroupsProxy, ddof: u8) -> Series {
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
return None;
}
let take = { self.take_unchecked(idx.into()) };
take.var_as_series(ddof)
.unpack::<Float64Type>()
.unwrap()
.get(0)
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let ca = self.cast(&DataType::Float64).unwrap();
ca.agg_var(groups, ddof)
} else {
_agg_helper_slice::<Float64Type, _>(groups_slice, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.var(ddof)
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_std(&self, groups: &GroupsProxy, ddof: u8) -> Series {
match groups {
GroupsProxy::Idx(groups) => agg_helper_idx_on_all::<Float64Type, _>(groups, |idx| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
return None;
}
let take = { self.take_unchecked(idx.into()) };
take.std_as_series(ddof)
.unpack::<Float64Type>()
.unwrap()
.get(0)
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let ca = self.cast(&DataType::Float64).unwrap();
ca.agg_std(groups, ddof)
} else {
_agg_helper_slice::<Float64Type, _>(groups_slice, |[first, len]| {
debug_assert!(first + len <= self.len() as IdxSize);
match len {
0 => None,
1 => NumCast::from(0),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.std(ddof)
}
}
})
}
}
}
}