在 Pandas 中计算 DataFrame 列中某个值的频率
pandasserver side programmingprogramming更新于 2025/9/29 3:13:00
要在 Pandas 中计算 DataFrame 列中某个值的频率,我们可以使用 df.groupby(column name).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 "列中值的频率", col, "is:
", count
col = "y"
count = df.groupby('y').size()
print "列中值的频率", col, "is:
", count
col = "z"
count = df.groupby('z').size()
print "列中值的频率", col, "is:
", count
输出
输入 DataFrame 为: x y z 0 5 4 1 1 2 10 1 2 1 5 5 3 5 10 1 x 列中值的频率为: x 1 1 2 1 5 2 dtype: int64 y 列中值的频率为: y 4 1 5 1 10 2 dtype: int64 z 列中值的频率为: z 1 3 5 1 dtype: int64

