如何在不使用熊猫的情况下操作CSV文件?

我有一个包含customer_id,order_id,number_of_items的CSV文件。由于存在重复项,因此我需要提出一个程序来查找每个客户购买的平均物品数和customer_ids的唯一数。我将如何处理此任务?我对于应该为此使用什么数据结构或者甚至如何做到这一点也感到困惑。我可以用Python或Java编写它。对我来说,这只是一次学习经历。我可以很容易地做到这一点,但是我想创建一个简单的程序来做到这一点。

zxf880820 回答:如何在不使用熊猫的情况下操作CSV文件?

使用CSV解析器读取文件,使用modal-backdrop收集不同的Set值,并计算项目总数。

伪代码

customer_id
,

这是awk中的一个(为了您的方便,用精美的字体印刷):

$ awk '
BEGIN {                                        # before anything
    FS=OFS=","                                 # set the field separators
}
NR>1 {                                         # skip header line,process others
    c[$1]++                                    # count the times a customer_id seen
    n[$1]+=$3                                  # total number of items purchased
}
END {                                          # after processing all transactions
    print "customer_id","avg_no_items"         # print header
    for(i in c) {                              # loop customer_ids in random order
        print i,n[i]/c[i]                      # compute avg and print
        u++                                    # count uniq customer_ids in c
    }
    print "Number of unique customer_ids: " u  # in GNU awk use length(c) and lose u
}' file

输出:

customer_id,avg_no_items
1,63.5
2,56
3,84
Number of unique customer_ids: 3

此处以承诺的单线形式:

$ awk 'BEGIN{FS=OFS=","}NR>1{c[$1]++;n[$1]+=$3}END{print "customer_id","avg_no_items";for(i in c){print i,n[i]/c[i];u++}print "Number of unique customer_ids: " u}' file
本文链接:https://www.f2er.com/3140052.html

大家都在问