0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pandasから出現回数のdictにする

Posted at

user:

pandas dataframe 形式のデータ df があります。列Xには、重複が多くあります。df から列Xを読み込んで、列Xに登場する文字列をkeyとして、その出現回数をvalueとする辞書形式データを得るPython関数を書いてください。


assistant:

以下のようなPython関数を作成することができます。Pandasを使用して、指定された列(X)に登場する文字列の出現回数をカウントし、それを辞書形式で返す関数です。

import pandas as pd

def count_occurrences(df, column_name):
    # 指定された列の値の出現回数をカウント
    counts = df[column_name].value_counts().to_dict()
    return counts

使用方法:

例えば、dfというDataFrameが以下のようなデータを持っている場合:

import pandas as pd

# 例として、以下のDataFrameを作成
data = {'X': ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']}
df = pd.DataFrame(data)

# 関数を呼び出して出現回数をカウント
result = count_occurrences(df, 'X')
print(result)

このコードを実行すると、出力は次のようになります:

{'apple': 3, 'banana': 2, 'orange': 1}

説明:

  • df[column_name].value_counts()は、指定された列(この例ではX)の各値が登場する回数をカウントして、pandas.Seriesオブジェクトを返します。
  • .to_dict()を使って、そのSeriesを辞書に変換しています。辞書のキーは値(文字列)、バリューはその出現回数になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?