【问题标题】:How to return the customer IDs of the best N customers from the transaction data如何从交易数据中返回最佳 N 个客户的客户 ID
【发布时间】:2022-01-15 18:51:33
【问题描述】:

我有一个 CSV 格式的交易数据,其中包含 Customer ID, Transaction Amount, Transaction Date 列。我有一个接受transactions_csv_file_path as string, N as an integer as params. I want to return the best N customers from the transaction data. NOTE:[最好的客户作为连续每日付款时间最长的客户]`的功能。我可以读取 CSV 如下:

public static string[,] ProcessCSV(string file_path, int n)
{
List<string> transData = new List<string>();
            using (StreamReader sr = new StreamReader(file_path))
            {
                
                string strResult = sr.ReadToEnd();
                var values = strResult.Split(',');
                transData.Add(values[0]);
                transData.Add(values[1]);

            }
return transData.ToArray();
}

调试时,我只得到没有数据的列标题。我想按日期获取每日连续付款并返回customerIds,例如:如果N=1,我希望输出为['K20008'],如果N=3, output: ['K20987', 'K20008', 'K20233']

如何从 CSV 中获取数组数据,并获得最佳的 N 个客户 ID 以及最长的连续每日付款时间?

考虑:define consecutive daily payments as at least 1 transaction per calendar day. and If there are any ties, use ascending order to break ties. For example, K20003 comes before K20005

【问题讨论】:

    标签: c# csv


    【解决方案1】:

    我也许会做一个计算最长运行长度的方法:

    int MaxRun(IEnumerable<DateTime> ds){
      int max = 0;
      int current = 0;
      var prev = DateTime.MinValue;
    
      foreach(var d in ds.Distinct().OrderBy(x => x)){
        if((d - prev).Days == 1)
          current++;
        else 
          current = 0;
        prev = d;
        if(current > max)
          max = current;
      }
      return max;
    }
    

    然后使用一点 LINQ 对人员进行分组,计算 maxrun,按 maxrun 排序转换,然后输出人员:

    transactions
      .GroupBy(t => t.Customer, t => t.TransactionDate )
      .Select(g => new { g.Key, MR = MaxRun(g) })
      .OrderBy(at => at.MR)
      .ThenBy(at => at.Key)
      .Select(at => at.Key)
      .ToArray()
    

    【讨论】:

    猜你喜欢
    • 2019-11-11
    • 2017-03-17
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多