计算 Pandas 中 DataFrame 列中某个值的频率
要计算Pandas中DataFrame列中某个值的频率,我们可以使用.方法。df.groupby(columnname)size()
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧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:\n", df
col = "x"
count = df.groupby('x').size()
print "列中值的频率 ", col, "is:\n", count
col = "y"
count = df.groupby('y').size()
print "列中值的频率 ", col, "is:\n", count
col = "z"
count = df.groupby('z').size()
print "列中值的频率 ", col, "is:\n", count输出结果Input DataFrame is: x y z 0 5 4 1 1 2 10 1 2 1 5 5 3 5 10 1 列中值的频率 x is: x 1 1 2 1 5 2 dtype: int64 列中值的频率 y is: y 4 1 5 1 10 2 dtype: int64 列中值的频率 z is: z 1 3 5 1 dtype: int64