我想在unix中对csv文件运行拆分,并在某些列上运行聚合。如果可能的话,我希望使用awk在每个拆分文件上分组几列。
有没有人知道可以做到这一点的一些unix魔法?
这是一个示例文件:
customer_id,location,house_hold_type,employed,income
123,Florida,Head,true,100000
124,NJ,NoHead,false,0
125,Florida,NoHead,true,120000
126,Florida,Head,true,72000
127,NJ,Head,false,0
我希望按条件对同一组的位置,house_hold_type以及AVG(收入)进行分组计数。
如何分割文件并使用它运行awk?
这是输出我期望输出的格式可能不同但是 这是我期待的整体数据结构。谦卑地接受其他呈现方式 信息:
location:[counts:['Florida':3, 'NJ':2], income_avgs:['Florida':97333, 'NJ':0]]
house_hold_type:[counts:['Head':3, 'NoHead':2], income_avgs:['Head':57333, 'NoHead':60000]]
提前谢谢你。
答案 0 :(得分:1)
awk最适合数据列,因此输入格式很好。可以管理输出格式,但在列中输出也会更简单:
#set the input and output field separators to comma
BEGIN {
FS = ",";
OFS = FS;
}
#skip the header row
NR == 1 {
next;
}
#for all remaining rows, store counters and sums for each group
{
count[$2,$3]++;
sum[$2,$3] += $5;
}
#after all data, display the aggregates
END {
print "location", "house_hold_type", "count", "avg_income";
#for every key we encountered
for(i in count) {
#split the key back into "location" and "house_hold_type"
split(i,a,SUBSEP);
print a[1], a[2], count[i], sum[i] / count[i];
}
}
示例输入:
customer_id,location,house_hold_type,employed,income
123,Florida,Head,true,100000
124,NJ,NoHead,false,0
125,Florida,NoHead,true,120000
126,Florida,Head,true,72000
127,NJ,Head,false,0
并输出:
location,house_hold_type,count,avg_income
Florida,Head,2,86000
Florida,NoHead,1,120000
NJ,NoHead,1,0
NJ,Head,1,0