統計 Pandas 中 DataFrame 列中某個值的頻率


要在 Pandas 中統計 DataFrame 列中某個值的頻率,我們可以使用 df.groupby(列名).size() 方法。

步驟

  • 建立一個二維可變性、潛在異構表格資料 df

  • 列印輸入 DataFrame,df

  • 列印列 x 的頻率。

  • 列印列 y 的頻率。

  • 列印列 z 的頻率。

示例

 即時演示

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 5],
      "y": [4, 10, 5, 10],
      "z": [1, 1, 5, 1]
   }
)

print "Input DataFrame is:
", df col = "x" count = df.groupby('x').size() print "Frequency of values in column ", col, "is:
", count col = "y" count = df.groupby('y').size() print "Frequency of values in column ", col, "is:
", count col = "z" count = df.groupby('z').size() print "Frequency of values in column ", col, "is:
", count

輸出

Input DataFrame is:
   x  y  z
0  5  4  1
1  2 10  1
2  1  5  5
3 5  10  1

Frequency of values in column x is:
   x
1  1
2  1
5  2
dtype: int64

Frequency of values in column y is:
   y
4  1
5  1
10 2
dtype: int64

Frequency of values in column z is:
   z
1  3
5  1
dtype: int64

更新日期: 30-8-2021

4000+ 次瀏覽

開啟你的 職業 生涯

完成該課程,獲得證書

開始學習
廣告