【Python】 DataFrame の特定の列で出現回数をカウントして降順でソートする方法。
Python で DataFrame 型の特定の列を指定して、対象列の文字列の出現回数をカウントして出現回数の降順(多い順)に並べる方法を紹介します。
DataFrame の「value_counts()」関数を使うと簡単に実現できました。
以下のような df という名前の DataFrame 型のデータがあるとします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
q_user_id r_user_id 0 akikirara1122 akikirara1122 1 akikirara1122 akikirara1122 2 asakaakie_blog2 asakaakie_blog2 3 a6789012002 casablanca117531 4 akikirara1122 amanjuli03 5 akikirara1122 asakaakie_blog2 6 akikirara1122 chanchankoiro 7 amanjuli03 ashino817 8 amanjuli03 casablanca117531 9 amanjuli03 chanchankoiro 10 asakaakie_blog2 ashino817 11 cotsplace cotsplace 12 ddogs38 ddogs38 13 fpdxw092 fpdxw092 14 fpdxw092 fpdxw092 15 ddogs38 fpdxw092 : |
「q_user_id」列の重複している各ユーザIDの出現回数をカウントします。
1 2 |
count = df['q_user_id'].value_counts() print(count) |
結果は、以下のようになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
tottokosa 6 akikirara1122 5 houzankai2006 3 amanjuli03 3 nama_k1 3 maruru39 2 ddogs38 2 sasaootako 2 nipponko2007 2 asakaakie_blog2 2 papakoa 2 umayado17 2 fpdxw092 2 cotsplace 1 juveneko 1 macyaken 1 a6789012002 1 saba2006201 1 tposato1 1 sanmamini91 1 wwide1225 1 Name: q_user_id, dtype: int64 |
結果は、Series 型で返り、index が 重複をカウントしたい要素(今回の場合は q_user_id 列)、data が 出現回数 となります。また、dtype は int64 となります。
Series 型は、インデックスとデータを持ちます。
なお、value_counts() はデフォルトで出現回数の降順(多い順)でソートしてくれます。
関連記事
-
【Python】時系列データ(為替データ)をグラフ表示してみた。
今回は、pandas・matplotlib ライブラリを使って、時系列データ(為替データ)をグラフ表
-
【Pandas】 DataFrame の行を抽出する方法【Python】
今回は、Python の Pandas で、DataFrame 型の行を抽出する方法を紹介します。
-
【Python】 複数の辞書型の同じ key を持つ value を計算に用いる方法。
Python で、複数の辞書型を読み込んで、同じキー(key)を持つ数値(value)を計算に使う方
-
【Pandas】 DetaFrame の列ごとに演算する方法【Python】
今回は、DetaFrame の列ごとに平均や加算・減算なのど演算をし、結果を DetaFrame 型
-
python 2.7 を Windows 64bit OS にインストールした。
python 2.7 を Windows にインストールしたときのメモです。 Python に
-
【Pandas】 DataFrame で2行の列ごとの差を計算する方法【Python】
今回は、Pandas の DataFrame で、2行間の列ごとの値の差を計算し、その結果を Dat
-
【Pandas】 DataFrame と Series のデータ構造について【Python】
今回は、Python でデータ分析を行っていると必ず使う Pandas の DataFrame と
-
【Python】Windows で ライブラリ(NumPy) をインストールする方法。
Windows の Python(2.X系)で NumPy をインストールしようと思ったら、そもそも
-
【Python】Requests ライブラリを使って Web ページを取得してみた。
python の標準ライブラリ urllib を使っても Web ページの取得はできるのですが、Re
-
【Google Colaboratory】クラウド上でPythonを使って機械学習を行う。
Python をブラウザ上で実行して、手軽に機械学習ができる環境「Google Colaborato