👩💻
言語処理100本ノック 2020 (Rev 2) 第2章: UNIXコマンド 19. 各行の1コラム目の文字列の出現頻度を求め,〜
問題
19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.確認にはcut, uniq, sortコマンドを用いよ.
solution19.py
import pandas as pd
df = pd.read_csv('chapter02/popular-names.txt', sep='\t', header=None)
print(df.iloc[:,0].value_counts())
#print(df[0].value_counts())
output
James 118
William 111
Robert 108
John 108
Mary 92
solution19.sh
cut -f 1 -d $'\t' popular-names.txt | LANG=C sort | uniq -c | sort -r -k 1 -t ' '
output
118 James
111 William
108 Robert
108 John
92 Mary
今回の問題では、pandas.Seriesのメソッドvalue_counts()
を使います。pandas.DataFrame
の列、pandas.Series
において、ユニークな要素の個数(重複を除いた件数)及び、それぞれの要素の頻度(出現回数)を取得できます。
Discussion