将numpy数字化函数翻译成c#

问题描述

Digitize 函数返回输入数组中每个值所属的 bin 的索引。

以下代码来自python -

x = np.array([0.8,6.9,3.5,1.9])
bins = np.array([0.0,1.0,2.5,4.0,10.0])
inds = np.digitize(x,bins)
print(inds)
array([1,4,3,2])

如何使用 C# 实现相同的结果?

解决方法

也许

public static IEnumerable<int> Digitize(double[] input,double[] source)
{
   foreach (var item in input)
      for (var index = 0; index < source.Length-1; index++)
         if (item > source[index] && item < source[index+1])
         {
            yield return index;
            break;
         }
}

测试

var input = new [] { 0.2,6.4,3.0,1.6 };
var bins = new[] { 0.0,1.0,2.5,4.0,10.0 };

var results = Digitize(input,bins);

Console.WriteLine(string.Join(",",results));

输出

0,3,2,1
,

您可以编写自己的数字化函数,该函数以两个数组为参数。

using System;

public class Test
{       
    static int findBinIndex(double input,double[] bins) {
        for(int i=1; i<bins.Length; i++){
           if(input < bins[i]) {
              return i;
           }
        }
        return bins.Length;
    }

    static void digitize(double[] x,double[] bins) {
        for(int i=0;i<x.Length;i++){
            System.Console.WriteLine(findBinIndex(x[i],bins));
        }
    }
    public static void Main()
    {
        double[] x = new double[] {0.8,6.9,3.5,1.9};
        double[] bins = new double[] {0.0,10.0};
        digitize(x,bins);
    }
}

您还可以使用 Array.BinarySearch 函数来提高执行时间。