「Pandas」行・列ごとの最頻値のリストを取得するサンプル

環境

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pandas 1.4.2
PyCharm 2021.3.3
pandas 1.4.2 PyCharm 2021.3.3
pandas 1.4.2
PyCharm 2021.3.3

構文
1.Series.mode(dropna=True)
シリーズのモードを返します。
モードは、最も頻繁に表示される値です。 複数のモードがあります。
値が1つだけ返される場合でも、常にSeriesを返します。

パラメーター
dropnabool、デフォルトはTrue
NaN/NaTの数を考慮しないでください。

戻り値 シリーズ
ソートされた順序でのシリーズのモード。
pandas.Seriesからmode()を呼ぶとpandas.Seriesが返ります

2.mode().tolist()
シリーズからリストへ変換します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
import pandas as pd
cft = pd.Series(['S', 'T', 'T', 'S'])
print("結果1")
print(cft)
print("結果2")
print(cft.mode())
print("最頻値のリストを取得する結果")
mlst= cft.mode().tolist()
print(mlst)
print(type(mlst))
# coding: utf-8 import pandas as pd cft = pd.Series(['S', 'T', 'T', 'S']) print("結果1") print(cft) print("結果2") print(cft.mode()) print("最頻値のリストを取得する結果") mlst= cft.mode().tolist() print(mlst) print(type(mlst))
# coding: utf-8
import pandas as pd

cft = pd.Series(['S', 'T', 'T', 'S'])
print("結果1")
print(cft)

print("結果2")
print(cft.mode())

print("最頻値のリストを取得する結果")
mlst= cft.mode().tolist()
print(mlst)

print(type(mlst))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
結果1
0 S
1 T
2 T
3 S
dtype: object
結果2
0 S
1 T
dtype: object
最頻値のリストを取得する結果
['S', 'T']
<class 'list'>
結果1 0 S 1 T 2 T 3 S dtype: object 結果2 0 S 1 T dtype: object 最頻値のリストを取得する結果 ['S', 'T'] <class 'list'>
結果1
0    S
1    T
2    T
3    S
dtype: object
結果2
0    S
1    T
dtype: object
最頻値のリストを取得する結果
['S', 'T']
<class 'list'>

 

Pandas

Posted by arkgame