【Pandas】统计某个值的出现次数
测试数据:
import pandas as pd
import numpy as np
df = pd.DataFrame({'key1':['a','a','b','b','a'],'key2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)})
统计key2中各个元素的出现次数:
df['key2'].value_counts()
结果:
one 出现3次
two 出现2次
分组统计:
按照 key1分组,统计key2列的值的出现次数
df['key2'].groupby(df['key1']).value_counts()