如何快速取得數值 GroupBy 結果 (CountIf, Group-Object, Counter)


  1. 說明
    1. Excel CountIf
    2. Powershell
    3. IPython REPL & Counter
    4. IPython REL & Pandas
    5. Node JS lodash

說明 SQL 常用的 Group By 資料操作,如何以其他程式語言來達到同樣的功能。包含以 Excel, PowerShell, Python (Pandas) 以及 JavaScript 作為示範 😉

logo

說明

以下是本次要處理的資料,目標是計算出各數值的出現次數:

plain.txt

1
2
3
1
2
1
1
1
5
2
3
4
1

結果應該如下呈現:

數值 次數
1 6
2 3
3 2
4 1
5 1

Excel CountIf

首先將資料貼上 Excel,並選取所有資料另貼上一欄,並移除重複的項目:

接著使用函式 CounfIf 並複製到各儲存格後就完成計算囉!

Powershell

get-content .\plain.txt | group-object | select name, count | convertto-json
"Name","Count"
"1","6"
"2","3"
"3","2"
"4","1"
"5","1"

IPython REPL & Counter

f = open('plain.txt')
lines = [line.strip() for line in f.readlines()]
# ['1', '2', '3', '1', '2', '1', '1', '1', '1', '2', '3', '4', '5']

from collections import Counter
Counter(lines)
# Counter({'1': 6, '2': 3, '3': 2, '4': 1, '5': 1})

IPython REL & Pandas

import pandas as pd
table = pd.read_table('plain.txt', header = None)
table.groupby(0).size()

# 0
# 1    6
# 2    3
# 3    2
# 4    1
# 5    1
# dtype: int64

Node JS lodash

const fs = require('fs')
arr = fs.readFileSync('plain.txt').toString().split('\r\n')
// ['1', '2', '3', '1', '2', '1', '1', '1', '1', '2', '3', '4', '5']

const _ = require('lodash')
_.countBy(arr)
// { '1': 6, '2': 3, '3': 2, '4': 1, '5': 1}