-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataFrameExtensionsCumulations.cs
More file actions
86 lines (78 loc) · 2.59 KB
/
DataFrameExtensionsCumulations.cs
File metadata and controls
86 lines (78 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Numerics;
using Microsoft.Data.Analysis;
namespace Dimension.DataFrame.Extensions;
/// <summary>
/// Cumulative extension methods to make Microsoft's DataFrame a little more user-friendly.
/// </summary>
public static class DataFrameExtensionsCumulations
{
public static PrimitiveDataFrameColumn<T> Cumulate<T>(this PrimitiveDataFrameColumn<T>? column, string newName = "", bool useNaN = false)
where T : unmanaged, INumber<T>
{
if (column is null)
{
throw new ArgumentNullException(nameof(column), "Column cannot be null.");
}
var newColumnName = string.IsNullOrEmpty(newName) ? column.Name + "_Cumulative" : newName;
var newColumn = new PrimitiveDataFrameColumn<T>(newColumnName, new T[column.Length]);
T? sum = T.Zero;
for (var i = 0; i < column.Length; i++)
{
var value = column[i];
if (value.HasValue && sum.HasValue)
{
sum += value.Value;
newColumn[i] = sum;
}
else
{
newColumn[i] = useNaN ? CreateNaN<T>() : default;
}
}
return newColumn;
}
public static PrimitiveDataFrameColumn<T> CumulateAbs<T>(this PrimitiveDataFrameColumn<T> column, string newName = "", bool useNaN = false)
where T : unmanaged, INumber<T>
{
if (string.IsNullOrEmpty(newName))
{
newName = column.Name + "_CumulativeAbs";
}
var newColumn = new PrimitiveDataFrameColumn<T>(newName, new T[column.Length]);
T? sum = T.Zero;
for (var i = 0; i < column.Length; i++)
{
var value = column[i];
if (value.HasValue && sum.HasValue)
{
var absValue = T.Abs(value.Value);
sum += absValue;
newColumn[i] = sum;
}
else
{
newColumn[i] = useNaN ? CreateNaN<T>() : default;
}
}
return newColumn;
}
// Utility method to generate NaN for supported types, default otherwise
private static T CreateNaN<T>()
where T : unmanaged, INumber<T>
{
if (typeof(T) == typeof(float))
{
return (T) (object) float.NaN;
}
else if (typeof(T) == typeof(double))
{
return (T) (object) double.NaN;
}
// Extend to other types if they support NaN
else
{
return default; // Fallback for types that do not support NaN
}
}
}